I have a common script which Im including in my PHPcron files and the files which are accessing through the browser. Some part of the code, I need only for non cron files. How can I detect whether the execution is from CLI or through browser (I know it can be done by passing some arguments with the cron files but I dont have access to crontab). Is there any other way ?
5 Answers
Use the php_sapi_name()
function.
if (php_sapi_name() == "cli") {
// In cli-mode
} else {
// Not in cli-mode
}
Here are some relevant notes from the docs:
php_sapi_name — Returns the type of interface between web server and PHP
Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.
-
4the PHP_SAPI can also be used for this, so it's not really the only right way to do this– mishuJul 22, 2014 at 9:18
-
There is a constant PHP_SAPI
has the same value as php_sapi_name()
.
(available in PHP >= 4.2.0)
I think you can see it from the $_SERVER variables. Try to print out the $_SERVER array for both browser & CLI and you should see differences.
-
1This may be true, but may not be a reliable way of determining the interface being used. The proper way to check is with
php_sapi_name()
. Jul 22, 2014 at 9:21
You can use:
if (isset($argc))
{
// CLI
}
else
{
// NOT CLI
}
-
5-1 -
$argc
could have been set within the application, couldn't it? Not a reliable method. Cost me half a day's work once.php_sapi_name()
is the only good way I know of.– PekkaMar 10, 2010 at 23:36 -
also $argv / $argc can be filled with GET variables on some configs! May 9, 2012 at 15:38
-
$argc could be disabled (not registered) in settings even for console apps– MikeDec 7, 2021 at 12:32