您应该将此脚本保留在公共文件夹之外。另外,为该文件设置适当的权限,以便公共用户无法执行该脚本。将下面的代码片段放在脚本的顶部。
if(php_sapi_name() !== 'cli'){
die('Can only be executed via CLI');
}
Run Code Online (Sandbox Code Playgroud)
请注意,在设置 cron 作业时,您需要使用 PHP 可执行文件的完整路径。例如:/usr/local/bin/php(您的路径可能与此不同)
正如这个重复线程中所解释的:
您应该将此文件保留在 public_html 之外。
但有时这是不可能的。我想到了Moodle,那里也有类似的功能。这就是他们所做的。
从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;
}
}
}
...
Run Code Online (Sandbox Code Playgroud)