Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if PHP script is running by shell [duplicate]

Tags:

php

Possible Duplicate:
In php, how to detect the execution is from CLI mode or through browser?

How can I check if a PHP script is running by Shell (command line) or by a server?

like image 718
paulodiovani Avatar asked Nov 26 '12 17:11

paulodiovani


3 Answers

Use the php_sapi_name function:

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

From the Manual:

Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using. For example, in CLI PHP this string will be "cli" whereas with Apache it may have several different values depending on the exact SAPI used. Possible values are listed below.

like image 195
MrCode Avatar answered Sep 28 '22 08:09

MrCode


Heres a shell solution if you are really interested in that :

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

Explination :

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.  
like image 34
gbtimmon Avatar answered Sep 28 '22 09:09

gbtimmon


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

Or

You can check for these:

if(isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'],"CLI") !== FALSE) {
 ///
}
like image 26
Ibu Avatar answered Sep 28 '22 07:09

Ibu