开发者

run php script only by cron

I k开发者_如何学Cnow 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.


Try to grant execute permissions only for the cron daemon user, maybe with that you get what you want.

Regards!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜