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?
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?
I'd try:
echo exec('whoami');
Usually webservers are run under a different username, so that should be telling.
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.
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;
}
}
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
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
My preferred method:
if (array_key_exists('SHELL', $_ENV)) {
echo "Console invocation";
}
else {
echo "HTTP invocation";
}