I have a crontab php script that resides in one of the folders on abc.tld. The problem is that the script could also be fired by calling it directly (i.e. http://abc.tld/crontab.php) To eliminate such possibility, I assume, I could do something like
if( isset($_SERVER['REQUEST_METHOD']) || isset($_SERVER['REMOTE_ADDR']) )
die( 'Never gonna happen!' );
But what is the right way? (except .htaccess)
Crontab entry:
0 12 * * 1 /usr/local/bin/php /home/pavellebedev/public_html/abc.tld/wp-content/plugins/easy-timesheet/kernel/cron/ezts_timesheet_notifications.php
Duplicate How to check if a php script is being called by another script on the server?
The answer :
The $_SERVER["REMOTE_ADDR"]
variable that gives you the IP address of the client who made the request should be 127.0.0.1
when the script is called from the server.
if(php_sapi_name() == 'cli') {
// Called from command-line, maybe cron
} elseif(php_sapi_name() == 'apache2handler') {
// Called from the apache2 webserver upon web request
}
Documentation : http://php.net/manual/en/function.php-sapi-name.php
As a conclusion of my research extended from Calimero's answer, here's the most reliable way to make sure that the script was called by crontab (php 5.3+):
if( stripos(php_sapi_name(), 'cgi') === false || stripos(php_sapi_name(), 'cli') === false ) die('Not cron');