Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run php script only by cron

Tags:

php

cron

I know 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!

like image 734
nirvanist Avatar asked Dec 10 '10 16:12

nirvanist


4 Answers

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)

like image 69
srimaln91 Avatar answered Nov 04 '22 21:11

srimaln91


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;
            }
        }
    }

...
like image 25
Roberto Aloi Avatar answered Nov 04 '22 20:11

Roberto Aloi


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

like image 1
Lekensteyn Avatar answered Nov 04 '22 22:11

Lekensteyn


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.

like image 1
Gideon Babu Avatar answered Nov 04 '22 22:11

Gideon Babu