I know how to run a script with a cron, but what I need is to be able to run my script only by a cron.
Thank you!
You should keep this script outside of the public folder. Also, set appropriate permissions to the file so public users can not execute the script. Put below code snippet to the top of your script.
if(php_sapi_name() !== 'cli'){
die('Can only be executed via CLI');
}
Note that you need to use the full path to the PHP executable when you setup your cron job. Ex : /usr/local/bin/php (Your path may be differ from this)
As explained in this duplicate thread:
PHP & cron: security issues
You should keep this file outside of public_html.
Sometimes, though, this is not possible. My mind went to Moodle, where a similar feature exists. This is what they do.
From cron.php
:
...
/// The current directory in PHP version 4.3.0 and above isn't necessarily the
/// directory of the script when run from the command line. The require_once()
/// would fail, so we'll have to chdir()
if (!isset($_SERVER['REMOTE_ADDR']) && isset($_SERVER['argv'][0])) {
chdir(dirname($_SERVER['argv'][0]));
}
...
/// check if execution allowed
if (isset($_SERVER['REMOTE_ADDR'])) { // if the script is accessed via the web.
if (!empty($CFG->cronclionly)) {
// This script can only be run via the cli.
print_error('cronerrorclionly', 'admin');
exit;
}
// This script is being called via the web, so check the password if there is one.
if (!empty($CFG->cronremotepassword)) {
$pass = optional_param('password', '', PARAM_RAW);
if($pass != $CFG->cronremotepassword) {
// wrong password.
print_error('cronerrorpassword', 'admin');
exit;
}
}
}
...
You need a PHP CLI/CGI executable for that. Assuming that the php
program is located at /usr/local/bin/php
, you can use:
/usr/local/bin/php /path/to/your/script.php
See also: http://nl.php.net/manual/en/features.commandline.usage.php
Please add this script at the top of your PHP file:
$isCLI = ( php_sapi_name() == 'cli' );
if( !$isCLI )
die("Sorry! Cannot run in a browser! This script is set to run via cron job");
and then if you try to run the PHP file via the browser, you cannot run it. This error message will be displayed. But at the same time, it can be run via a cron job.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With