I have a PHP script which can be run from either crontab jobs list and from Apache (by implementing it's web address into web-browser). The behavior of the script should be different in those cases. How can I find out how the script was run?
Asked
Active
Viewed 181 times
0
-
1There're many people that use crontab to execute PHP scripts through `wget` or similar HTTP tools. I suppose you call PHP from the command-line. – Álvaro González Jan 23 '14 at 11:20
1 Answers
2
You can use the function php_sapi_name()
to detect on which SAPI the script is running.
Like this:
if(in_array(php_sapi_name(), array(
'apache',
'apache2filter',
'apache2handler'
))) {
echo "we are running on apache";
} else {
echo "we are not running on apache";
}
However, the fact that the script isn't running by apache does not necessarily mean that the script is run by cron. It is also possible that you've launched it manually via the command line. The safest way would be to pass a param from cron:
* * * * * user_name php /path/to/your.php cron
Then in the script you might check:
if(isset($argv[1]) && $argv[1] === 'cron') {
echo "we are running as a cron job";
}

hek2mgl
- 152,036
- 28
- 249
- 266
-
If I run my script from web - this function returning 'cgi-fcgi'. But I get the idea, thank you! – Roman Matveev Jan 23 '14 at 11:18
-
1@RomanMatveev Yeah, you should refine the check according your needs.. However, the safest way might be to just pass the param from cron – hek2mgl Jan 23 '14 at 11:20