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.5k times
5 Answers
187
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,194
- 5
- 31
- 53
Alexander V. Ilyin
- 2,296
- 1
- 15
- 11
-
2+1 the only right way to do it. – Pekka Mar 10 '10 at 23:34
-
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
-
18This used to be a link only answer until someone copied @Linus Unnebäck's answer. Bad habbit! Downvote this one, upvote the other one... – Gottlieb Notschnabel Apr 01 '15 at 13:55
-
7@GottliebNotschnabel Thank you! Very annoying to see this happening. – Linus Unnebäck Jun 18 '15 at 08:35
-
2Pinching somebody else's help, tsk, tsk. Really not very awesome, dude. – Sep 09 '15 at 08:03
-
@mishu yes, PHP_SAPI is the best way! – Ankit Jan 14 '16 at 23:34
87
if(php_sapi_name() == "cli") {
//In cli-mode
} else {
//Not in cli-mode
}
Linus Unnebäck
- 20,208
- 12
- 69
- 83
22
There is a constant PHP_SAPI has the same value as php_sapi_name().
(available in PHP >= 4.2.0)
Andy Fleming
- 7,194
- 5
- 31
- 53
just somebody
- 17,784
- 6
- 49
- 58
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,510
- 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
- 22,744
- 4
- 30
- 29
-
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