簡體   English   中英

只有cron才能運行php腳本

[英]run php script only by cron

我知道如何使用cron運行腳本,但我需要的是只能通過cron運行我的腳本。

謝謝!

如此重復帖子中所述:

PHP和cron:安全問題

您應該將此文件保留在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;
            }
        }
    }

...

您應該將此腳本保留在公用文件夾之外。 此外,為文件設置適當的權限,以便公共用戶無法執行腳本。 將下面的代碼段放在腳本的頂部。

if(php_sapi_name() !== 'cli'){
    die('Can only be executed via CLI');
}

請注意,在設置cron作業時,需要使用PHP可執行文件的完整路徑。 例如:/ usr / local / bin / php(您的路徑可能與此不同)

您需要一個PHP CLI / CGI可執行文件。 假設php程序位於/usr/local/bin/php ,您可以使用:

/usr/local/bin/php /path/to/your/script.php

另見: http//nl.php.net/manual/en/features.commandline.usage.php

請在PHP文件的頂部添加此腳本:

$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作業運行。

嘗試僅為cron守護程序用戶授予執行權限,也許可以獲得所需的權限。

問候!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM