In PHP, how to detect the execution is from CLI mode or through browser ?
PhpPhp Problem Overview
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 ?
Php Solutions
Solution 1 - Php
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.
Solution 2 - Php
if(php_sapi_name() == "cli") {
//In cli-mode
} else {
//Not in cli-mode
}
Solution 3 - Php
There is a constant PHP_SAPI
has the same value as php_sapi_name()
.
(available in PHP >= 4.2.0)
Solution 4 - Php
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.
Solution 5 - Php
You can use:
if (isset($argc))
{
// CLI
}
else
{
// NOT CLI
}