• 3
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

How to check if cronjob exists with PHP?

Is there a way to know if a cronjob already exists with php?

I want it to work on most hostings, even shared.

NO, There's no such direct privilege in PHP.

But (On Dedicated Server) you can write a PHP script to read /etc/crontab file and parse the info to check if a specific cron exists on the server.

  • 11
Reply Report

You could try running the crontab -l command, which should work from PHP. You might have to qualify the full path, e.g., /usr/bin/crontab -l, which would depend on the host.

This will return the crontab entries for the user who runs the command, which is what you want if the PHP page and cron jobs run as the same user (many shared hosts use setuid php scripts these days). To get the crontab entries for another user you'd need superuser rights on most systems, and crontab -l -u otheruser.

  • 3
Reply Report

using shell_exec() or system() or something like that might solve the problem. But it won't work with safe_mode turned on.

and i think shared hostings won't have these features enabled.

@Nathan: wouldn't /usr/bin/crontab -l be returning the crontab for the user who runs the script? e.g. www-data, wwwrun, apache or something?

  • 1
Reply Report
    • yes... I guess I'm assuming most shared hosts have user PHP scripts running setuid as the user, same as their cron jobs. I'll edit to clarify my answer.

In addition to Nathan's answer:

If you can run exec() and the crontab command

function cronjob_exists($command){

    $cronjob_exists=false;

    exec('crontab -l', $crontab);

    if(isset($crontab)&&is_array($crontab)){

        $crontab = array_flip($crontab);

        if(isset($crontab[$command])){

            $cronjob_exists=true;

        }

    }

    return $cronjob_exists;
}

$command = '30 9 * * * '.__DIR__.'/cronjobs/job1.php';

if(cronjob_exists($command)===FALSE){

    //add job to crontab
    exec('echo -e "`crontab -l`\n'.$command.'" | crontab -');

}
  • 1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions