Run PHP script only cron

I know how to run a script using cron, but I need to be able to run my script only cron.

Thank!

+5
source share
5 answers

As explained in this recurring thread:

PHP and cron: security issues

You must store this file outside of public_html.

Sometimes, however, this is not possible. My mind went to Moodle , where a similar function 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;
            }
        }
    }

...
+3
source

To do this, you need the PHP CLI / CGI executable. Assuming the program phpis in /usr/local/bin/php, you can use:

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

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

0

script . , , script. script.

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

, cron PHP. :/usr/local/bin/php ( )

0

, script 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.

0

Try to grant execution permissions only for the cron daemon user, perhaps with it you will get what you want.

Hello!

-2
source

All Articles