Quick way to determine if php is running at the command line

Many times it is necessary to determine if the php script is running on the command prompt. Recently I wrote a php shell script which could also be run from a browser and needed to decide in the code if to output a '\n' or a ‘html break’ after a text line.

The following simple function returns a true if the script is run from a command prompt and false otherwise.

It uses the php_sapi_name() function, which returns a string that describes the type of interface PHP is using. The possible return values of the php_sapi_name() function include: aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.

<?php
 
function isCli() {
 
     if(php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
          return true;
     } else {
          return false;
     }
}
 
?>
cli

10 thoughts on “Quick way to determine if php is running at the command line

  1. Great! Thank you!
    But i think we can make it shorter with this command:
    return (php_sapi_name() == ‘cli’ && empty($_SERVER[‘REMOTE_ADDR’]))

  2. Aren’t you also able to check the count of argc? If called from the command line, it will exist in the $_SERVER superglobal and its count will be at least one (the first item being the name of the file):

    $using_cli = (@$_SERVER[‘argc’] >= 1);

  3. $_SERVER[‘REMOTE_ADDR’] would throw a warning if it’s not set. Check to see if it exists before checking it’s value.

    Either way, this was helpful, thanks!

  4. Jorge: empty() will act in the same way as isset() with regards to indices not being set.
    if (empty($_SERVER[‘non_existant’])) will not cause an error to be thrown.

  5. Why use anything to test that? if php_sapi_name() == ‘cli’ then you are running from the command line. Full stop. There is no need to test whether $_SERVER[‘REMOTE_ADDR’] is empty or not.

  6. David >> No you need to do that check, if you etc use php-cli via cgi/apache or cgi-fast interface you actually call the php from commandline but you still get the http enviroment variables.

    Cheers

Comments are closed.