Php check if script running

How to Check if php is running from cli (command line)

PHP scripts are usually opened in a web browser. But they can be run from command line or terminal as well. The syntax to run a script from commandline is very much similar to python or perl.

Inside a script it might be necessary to test if it is being run from command line or not. For example when a script is being from cron it might produce a different kind of output than when it is run from a browser url. In such cases the script needs to identify its running mode.

There are several ways to check if a php script is running from cli or not. Lets check them one by one

1. Check for the STDIN constant. STDIN is a constant that is defined when php is running from command line.

if(defined('STDIN') ) echo("Running from CLI"); else echo("Not Running from CLI");

However the above method has certain limitations. The test works very well when the script is being run using the php cli binary. In cronjobs for example a the command is specified as follows

Now the php command itself points to a php binary which can be either the php-cli binary or php-cgi binary. If it points to a php-cgi binary, like it happens on some hosting servers then the STDIN check will always be false. So the STDIN check method is not fully reliable. Lets take a look at another method for checking cli.

Читайте также:  Php массив файлов папке

2. Check the php_sapi_name. The php_sapi_name function is supposed to return «cli» if the script is running from commandline.

if(php_sapi_name()==="cli") echo("Running from CLI"); else echo("Not Running from CLI");

But this method too suffers the same problem as STDIN. It will work only if the cli mode has been triggered by the php cli binary. If php-cgi was used to initiate the script from the command line, it would always return «cgi-fcgi» for example.

3. Check the PHP_SAPI constant. The PHP_SAPI constant is the same as php_sapi_name function. So it has the same issues as mentioned above.

if (PHP_SAPI === 'cli') echo("Running from CLI"); else echo("Not Running from CLI");

For cgi this approach can be useful :

if(stristr(PHP_SAPI , 'cgi') and getenv('TERM')) echo("Running from CLI"); else echo("Not Running from CLI");

Working Solution

On servers that have fastcgi as the php handler for example, the php binary might point to php-cgi. So to test cli in an interface independant manner a different kind of check has to be done. Which is to check the contents of the $_SERVER variable for example.

function is_cli() < if( empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) >0) < return true; >return false; >

The above method should properly detect cli in all cases. Can add an STDIN check too.

function is_cli() < if( defined('STDIN') ) < return true; >if( empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) < return true; >return false; >

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

4 Comments

  1. How ToSeptember 6, 2021 at 3:03 am Not exactly related to the topics, but I am facing a problem related to this. When I run ps -aux in my Namecheap server, it shows PHP processes wither the filenames, but when I run the same px -aux command in y VPS (with LAMP, i do not get the filenames but simply /usr/sbin/apache2 -k start
    Any idea how to make my LAMP server in my VPS to show PHP filenames when I execute ps -aux ?

Источник

Check if PHP script is running, and if not run it

This listens for a particular port and does actions according to the input. The problem is that sometimes the script stops. I cannot use a cron job to fix this, because my server is listening to a port all the time and also is creating child processes. Is there a way to check if server.php is running and (if not) start it?

Make server.php listen on an UNIX domain socket, and answer with its status when queried. Poll it from cron every few minutes, and restart it if it doesn’t answer.

3 Answers 3

You can check for the process using ps , but one drawback is that if you have multiple instances of this process running or if the script is hung up then this method can be less than conclusive.

I prefer to actually check if the server is listening on the port. Here are a couple of ways to do this. If your server is listening on port 2000 for example consider the following.

Using lsof

lsof is checking for open file descriptors and should show whether or not a program is listening or actively communicating on this port. This will echo either a 0 if the server is accepting connections on port 2000 or a 1 if it is not.

Using nc

nc -z -w1 192.168.1.12 2000 &> /dev/null; echo $?; 

This is my preferred method for checking on a socket server. Here nc is using the -z flag for zero I/O mode to quickly scan the port. You can use your IP address here and the correct port. If the server is accepting connections then life is good.

Again here return values will be either a 0 for good or a 1 for not good. We are discarding any output here because we are wanting just a quick boolean check. This method returns very fast if the network address is reachable. Run from the server itself you will not see hardly any latency as it is trying to talk to itself.

Automating

To run these tests via cron, create a bash script and execute one or both of these commands and run through a series of logical checks. If they fail restart your script and recheck. I have been using these methods for several years now and have had very good results of practical uptime.

Источник

Php check if executable is running

You would only be able to check server-side processes, where PHP is running. JavaScript (client-side) isn’t allowed that kind of access because of security. , How do keep pee from splattering from the toilet all around the basin and on the floor on old toilets that are really low and have deep water? , 4 You would only be able to check server-side processes. JavaScript (client-side) isn’t allowed that kind of access because of security. – Jay Blanchard Aug 3 ’16 at 13:05 ,For a Windows-specific solution, you can execute the shell command tasklist with the proper options (see tasklist /?). On Unix-based, you would use ps.

I understand you are using cli or want to check server-side processes.

For a Windows-specific solution, you can execute the shell command tasklist with the proper options (see tasklist /? ). On Unix-based, you would use ps .

I understand you are using cli or want to check server-side processes.

For a Windows-specific solution, you can execute the shell command tasklist with the proper options (see tasklist /? ). On Unix-based, you would use ps .

I understand you are using cli or want to check server-side processes.

For a Windows-specific solution, you can execute the shell command tasklist with the proper options (see tasklist /? ). On Unix-based, you would use ps .

Answer by Bridget Saunders

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL),Don’t tell someone to read the manual. Chances are they have and don’t get it. Provide an answer or move on to the next question. , communitylounge Who’s Who Most Valuable Professionals The Lounge The CodeProject Blog Where I Am: Member Photos The Insider News The Weird & The Wonderful ,If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.

if (isset($_POST['Initiate'])) < $shell = new COM("WScript.Shell") or die("Requires Windows Scripting Host"); $exePath = "TestDlg.exe"; $shell->exec($exePath); //this is launching the application successfully >

Answer by Alianna Magana

On the above code, we use the PHP tasklist command to see what processes are running in Windows.,3 How to Kill Windows Process Using PHP3.1 Code Explanation:,To Check Process Running in Windows using PHP, we have to use PHP tasklist command with exec() function.,exec is the PHP inbuilt function used to execute an external program and return the last value, if there is no return then it returns the NULL value.

Introduction

T o Check Process Running in Windows using PHP, we have to use PHP tasklist command with exec() function.

Answer by Isaac White

Check if a process is running on a Linux system such as Ubuntu by using PHP. This is done by using pgrep and checking if its response is empty.,Now for a check to simply return yes or no upon the process running:,The above command is if youtube-dl has at least one instance running then the process id/s will be returned.,To check for FFmpeg running you would do pgrep FFmpeg and it would return all the process id’s (PID) for instances of FFmpeg running.

To check for FFmpeg running you would do pgrep FFmpeg and it would return all the process id’s (PID) for instances of FFmpeg running.

echo shell_exec("pgrep youtube-dl");

Now for a check to simply return yes or no upon the process running:

if (empty(trim(shell_exec("pgrep youtube-dl")))) < echo "No"; >else

Here it is put into a function that can be re-used fro different process names i.e FFmpeg, Wget, PHP etc:

function processRunning(string $process): bool < if (empty(trim(shell_exec("pgrep $process")))) < return false; >else < return true; >>

Answer by Zane Delacruz

Check if a PHP script is already running If you have long running batch processes with PHP that are run by cron and you want to ensure there’s only ever one running copy of the script, you can use the functions getmypid() and posix_kill() to check to see if you already have a copy of the process running. This post has a PHP class for checking if the script is already running.,If, though, you are certain that the script should only ever be running once, then it’s relatively easy to check from within the script whether it is already running when you start it. Here’s some code:,I know this is an old question but in case someone else is looking here I’ll post some code. This is what I have done recently in a similar situation and it works well. Put put this code at the top of your file and if the same script is already running it will leave it be and end the new one.,Simply call this function at the start of the script, before you do anything else (such as open a database handler or process an import file), and if the same script is already running then it will appear twice in the process list — once for the previous instance, and once for this one. So, if it appears more than once, just exit.

Here’s a copy/paste-ready implementation:

#!/usr/bin/php else if (!$got_lock && $wouldblock) < exit("Another instance is already running; terminating.\n"); >// Lock acquired; let's write our PID to the lock file for the convenience // of humans who may wish to terminate the script. ftruncate($lock_file, 0); fwrite($lock_file, getmypid() . "\n"); /* The main body of your script goes here. */ echo "Hello, world!"; // All done; we blank the PID file and explicitly release the lock // (although this should be unnecessary) before terminating. ftruncate($lock_file, 0); flock($lock_file, LOCK_UN); 

Answer by Fernando Mendoza

The is_executable() function in PHP is an inbuilt function which is used to check whether the specified file is an executable file or not. The name of the file is sent as a parameter to the is_executable() function and it returns True if the file is an executable file else it returns False.,The result of this function are cached and therefore the clearstatcache() function is used to clear the cache.,is_executable() function returns false for non-existent files.,Parameters Used:The is_executable() function in PHP accepts one parameter.

Executable file and File Permissions are : 0644 

Answer by Clare Kemp

If you have long running batch processes with PHP that are run by cron and you want to ensure there’s only ever one running copy of the script, you can use the functions getmypid() and posix_kill() to check to see if you already have a copy of the process running. This post has a PHP class for checking if the script is already running.,The class tidies up the pid file at the end of the script run automatically in the desctructor, so all you need to do is create the object at the start and then check to see if it’s already running.,To test it, you could add «sleep(30);» to the end of the test script above, run the script and then run the script again. The second time you run it the script will output «Already running» and exit.,Each process running on a Linux/Unix computer has a pid, or process identifier. In PHP this can be retrieved using getmypid() which will return an integer number. This pid number can be saved to a file and each time the script is run a check made to see if the file exists. If it is the posix_kill() function can be used to see if a process is running with that pid number.

class pid < protected $filename; public $already_running = false; function __construct($directory) < $this->filename = $directory . '/' . basename($_SERVER['PHP_SELF']) . '.pid'; if(is_writable($this->filename) || is_writable($directory)) < if(file_exists($this->filename)) < $pid = (int)trim(file_get_contents($this->filename)); if(posix_kill($pid, 0)) < $this->already_running = true; > > > else < die("Cannot write to pid file '$this->filename'. Program execution halted.n"); > if(!$this->already_running) < $pid = getmypid(); file_put_contents($this->filename, $pid); > > public function __destruct() < if(!$this->already_running && file_exists($this->filename) && is_writeable($this->filename)) < unlink($this->filename); > > > 

and it can be used as follows:

$pid = new pid('/tmp'); if($pid->already_running) < echo "Already running.n"; exit; >else

Источник

Оцените статью