tags:

views:

186

answers:

7

I need to determine whether the current invocation of PHP is from the command line (CLI) or from the web server (in my case, Apache with mod_php).

Any recommended methods?

A: 

I'd try:

echo exec('whoami');

Usually webservers are run under a different username, so that should be telling.

Stefan Mai
A: 

Try

isset($_SERVER['REQUEST_METHOD'])

if it's set, you're in a browser.

Alternatlely, you could check if

isset($_SERVER['argv'])

but that might not be true on windows CLI, IDK.

gnud
A: 

I would suggest to check if some of the entries of the $_SERVER array are set.

E.g.:

if (isset($_SERVER['REQUEST_METHOD'])) {
        print "HTTP request\n";
} else {
        print "CLI invocation\n";
}
rodion
+17  A: 

php_sapi_name is the function you will want to use as it returns a lowercase string of the interface type. In addition, there is the PHP constant PHP_SAPI.

Documentation can be found here: http://php.net/php_sapi_name

For example, to determine if PHP is being run from the CLI, you could use this function:

function isCommandLineInterface()
{
    if (php_sapi_name() === 'cli')
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
Jordan S. Jones
Whoa- I had no idea :D
gnud
More straightforward: `return php_sapi_name() == 'cli';`
Savageman
+3  A: 

i think he means if PHP CLI is being invoked or if it is a response from a web request. The best way would be to use

php_sapi_name()

which if it was running a web request would echo apache if that is what it was running. a list of a few:

*  aolserver
* apache
* apache2filter
* apache2handler
* caudium
* cgi
* cgi-fcgi
* cli
* Continuity
* embed
* isapi
* milter
* nsapi
* phttpd
* pi3web
* roxen
* thttpd
* tux
* webjames
Marc Towler
A: 

According to http://jp2.php.net/manual/en/features.commandline.php There are a number of constants set only when running from the CLI. These constants are STDIN, STDOUT and STDERR. Testing for one of those will tell you if it is in cli mode

Jonathan Fingland
+1  A: 

My preferred method:

if (array_key_exists('SHELL', $_ENV)) {
  echo "Console invocation";
}
else {
  echo "HTTP invocation";
}
Travis Beale