5

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?

Community
  • 1
  • 1
paulodiovani
  • 1,208
  • 2
  • 16
  • 34

4 Answers4

11

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.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • hi @mrCode is iot possible to run a CLI command inside a php function in form of a snippet ? using shell_exec() ? – Fasih Sajid Dec 20 '20 at 11:30
7

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.  
gbtimmon
  • 4,238
  • 1
  • 21
  • 36
2

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) {
 ///
}
Ibu
  • 42,752
  • 13
  • 76
  • 103
1

this works in my product environment:

if( substr(php_sapi_name(), 0, 3) == 'cli' ) {
    die("You Should Use CGI To Run This Program.\n");
}
dennisyuan
  • 171
  • 1
  • 10
  • Is the `substr` really necessary? – Brendan Long Nov 26 '12 at 17:52
  • I have tested the php_sapi_name function on Debian 9 with PHP 7.0 and with systemd services/timers, cron jobs and manually running /usr/bin/php in the cli they all return a value of 'cli'. So it seems like currently the substr isn't actually necessary. A comment on the documentation page says that cron jobs return a value of cli-fcgi, but I guess that isn't true anymore. – Infineight May 02 '19 at 10:02