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


Posted in: php | Save to del.icio.us | 25 Jul 2009



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;
     }
}
 
?>





4 Responses

1

kureikain

July 25th, 2009 at 11:19 am

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

2

Alex

July 26th, 2009 at 2:26 pm

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

Jorge

April 3rd, 2010 at 10:27 am

$_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

Rob

May 20th, 2010 at 5:03 pm

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.

Comments are disabled for this post, but if you have spotted an error, feel free to contact me.

Get latest updates by E-mail

About this blog

This site is a digital habitat of Sameer, a freelance web developer working from Pune.More

  • Users Online

    • 8 Users Online
    • 6 Guests, 2 Bots
  • RECENT COMMENTS

    ON TWITTER