I need to determine whether the PHP file is being loaded via cron or command line within the code. How can I do this?
Asked
Active
Viewed 6,166 times
9
-
Loaded into what? In what environment? – wallyk Dec 06 '09 at 04:05
-
Duplicate: http://stackoverflow.com/questions/1848803/execute-php-via-cron-no-input-file-specified – Doug Neiner Dec 06 '09 at 04:26
4 Answers
16
If you have control over the cron or command, have you considered passing a command-line argument, and reading it with $_SERVER['argv'][0]?
* * * * * /usr/bin/php /path/to/script --cron
In the script:
<?php
if(isset($_SERVER['argv'][0]) and $_SERVER['argv'][0] == '--cron')
$I_AM_CRON = true;
else
$I_AM_CRON = false;
gahooa
- 131,293
- 12
- 98
- 101
-
1Worked for me, although in my case I had to use `$_SERVER['argv'][1]` :) – bbeckford Jan 22 '14 at 11:01
6
The most reliable and exhaustive way to check where your script is run known to me is
Neither this nor any of the other listed methods listed here, however, will give you a distinction between "normal" CLI mode, and a cron call. gahooa's command line argument idea is probably the best and most reliable solution.
Adam Michalik
- 9,678
- 13
- 71
- 102
Pekka
- 442,112
- 142
- 972
- 1,088
-
I'm not sure if something has changed in the last several years, but on my system (CentOS 6.6, PHP 5.4.38, running Litespeed), there is a distinction. `php_sapi_name()` returns `cli` when run from the command-line. It returns `cgi-fcgi` when run via cron. – rinogo Mar 05 '15 at 17:45
6
This is one simple way. Certain elements of the $_SERVER array are only set if called from HTTP. Thus you can:
if(!isset($_SERVER['REQUEST_METHOD'])){
// from cron or command line
}else{
// from HTTP
}
Others include: $_SERVER['HTTP_HOST']
mauris
- 42,982
- 15
- 99
- 131
2
You can check the PHP_SAPI constant to check if the CLI interpreter is being used:
$is_cli= PHP_SAPI == 'cli';
leepowers
- 37,828
- 23
- 98
- 129
-
Though irrelevant here, there is very little reason to ever use the `==` operator. – Nate Higgins Jun 05 '13 at 21:01