run php script only by cron

0 votes
asked Dec 10, 2010 by nirvanist

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!

4 Answers

0 votes
answered Dec 10, 2010 by lobo

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


0 votes
answered Dec 10, 2010 by lekensteyn

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:

0 votes
answered Dec 10, 2010 by roberto-aloi

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])) {


/// 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');
        // 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'); 

0 votes
answered Sep 15, 2017 by srimaln91

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)

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter