How to check if a PHP script works as a shell

Possible duplicate:
In php, how to detect execution from CLI mode or through a browser?

How to check if a php script is running using shell command line or command line?

+4
source share
4 answers

Use the php_sapi_name function:

 if(php_sapi_name() == 'cli') { // running from CLI } 

From Manual :

Returns a string string describing the type of interface (server API, SAPI) that PHP uses. For example, in the CLI PHP this line will be "cli", whereas with Apache it can have several different values โ€‹โ€‹depending on the exact SAPI used. Possible values โ€‹โ€‹are listed below.

+9
source

Here is a shell solution if you are really interested in this:

 ps -ef | grep $scriptname | grep -v grep; if [[ $? -eq 0 ]]; then echo "PROCESS IS RUNNING"; fi 

Explanation:

 ps -ef ## lists all running processes grep $scriptname ## keep only the process with the name we suppply grep -v grep ## the previous grep will show up in the ps -ef so this prevents false positives. if [[ $? -eq 0 ]]; then echo "PROCESS IS RUNNING"; fi ## if the last line returns something then process is running. 
+5
source

You can check for the presence of the $argv variable.

or

You can check them out:

 if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],"CLI") !== FALSE) { /// } 
+2
source

this works in my product environment:

 if( substr(php_sapi_name(), 0, 3) == 'cli' ) { die("You Should Use CGI To Run This Program.\n"); } 
0
source

All Articles