In PHP, how to detect execution from CLI mode or through a browser?

I have a generic script that Im includes in my PHPcron files and files that are viewed through the browser. Some of the code I need is only for non cron files. How can I determine if execution is done from the CLI or through the browser (I know that this can be done by passing some arguments with cron files, but I do not have access to crontab). Is there another way?

+72
php
Jan 02 '09 at 11:33
source share
5 answers

Use php_sapi_name() .

 if (php_sapi_name() == "cli") { // In cli-mode } else { // Not in cli-mode } 

Here are some important notes from the docs:

php_sapi_name - returns the type of interface between the web server and PHP

Although not exhaustive, possible return values ​​include aolserver, apache, apache2filter, apache2handler, caudium, cgi (before PHP 5.3), cgi-fcgi, cli, cli-server, continuity, embedding, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux and webjames.

+134
Mar 10 '10 at 23:33
source share
 if(php_sapi_name() == "cli") { //In cli-mode } else { //Not in cli-mode } 
+59
Apr 04 '10 at
source share

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

(available in PHP> = 4.2.0)

+13
Jan 02 '09 at 11:39
source share

I think you can see this from the $ _SERVER variables. Try printing the $ _SERVER array for the browser and CLI, and you should see the differences.

+3
Jan 02 '09 at 11:39
source share

You can use:

 if (isset($argc)) { // CLI } else { // NOT CLI } 
-four
Jan 02 '09 at 11:40
source share