我知道如何在cron中运行脚本,但我需要的是只能通过cron来运行我的脚本。
谢谢!
谢谢!
if(php_sapi_name() !== 'cli'){
die('Can only be executed via CLI');
}
正如在这个重复的线程中所解释的那样:
您应该将此文件保存在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;
}
}
}
...
$isCLI = ( php_sapi_name() == 'cli' );
if( !$isCLI )
die("Sorry! Cannot run in a browser! This script is set to run via cron job");
如果您尝试通过浏览器运行PHP文件,则无法运行它,会显示此错误消息。但同时,它可以通过cron作业运行。
php
程序位于 /usr/local/bin/php
,你可以使用以下命令:/usr/local/bin/php /path/to/your/script.php
另请参阅:http://nl.php.net/manual/zh/features.commandline.usage.php
尝试仅为cron守护程序用户授予执行权限,也许这样你就能得到想要的结果。
敬礼!