109

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 ?

0

5 Answers 5

198

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.

2
  • 4
    the PHP_SAPI can also be used for this, so it's not really the only right way to do this
    – mishu
    Jul 22, 2014 at 9:18
  • @mishu yes, PHP_SAPI is the best way!
    – Ankit
    Jan 14, 2016 at 23:34
91
if(php_sapi_name() == "cli") {
    //In cli-mode
} else {
    //Not in cli-mode
}
23

There is a constant PHP_SAPI has the same value as php_sapi_name().

(available in PHP >= 4.2.0)

0
3

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.

1
  • 1
    This 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
-6

You can use:

if (isset($argc))
{
    // CLI
}
else
{
    // NOT CLI
}
3
  • 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.
    – Pekka
    Mar 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
    – Mike
    Dec 7, 2021 at 12:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.