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 ?
Asked
Active
Viewed 5.9k times
5 Answers
199
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.

Andy Fleming
- 7,655
- 6
- 33
- 53

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

Linus Unnebäck
- 23,234
- 15
- 74
- 89
23
There is a constant PHP_SAPI
has the same value as php_sapi_name()
.
(available in PHP >= 4.2.0)

Andy Fleming
- 7,655
- 6
- 33
- 53

just somebody
- 18,602
- 6
- 51
- 60
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.

Jimmy Shelter
- 1,540
- 9
- 13
-
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()`. – Andy Fleming Jul 22 '14 at 09:21
-6
You can use:
if (isset($argc))
{
// CLI
}
else
{
// NOT CLI
}

Etienne Dechamps
- 24,037
- 4
- 32
- 31
-
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 '10 at 23:36
-
also $argv / $argc can be filled with GET variables on some configs! – Tomáš Fejfar May 09 '12 at 15:38
-
$argc could be disabled (not registered) in settings even for console apps – Mike Dec 07 '21 at 12:32