skip to Main Content

I want to edit crontab from PHP script.

$output = shell_exec('crontab -l');

            echo "<pre>";
            print_r($output);
            echo "</pre>";

This is returned.

MAILTO="[email protected]"
*/2 *   *   *   *   /usr/bin/php5 /var/www/vhosts/example.com/streaming.example.com/index.php admin cron  > /dev/null
MAILTO=""
*/1 *   *   *   *   /opt/psa/admin/sbin/fetch_url 'https://www.example.com/referral/send_referral_email'
MAILTO=""
*/5 *   *   *   *   /opt/psa/admin/sbin/fetch_url ' https://www.example.com/members/send_notif'
MAILTO="[email protected]"
*/2 *   *   *   *   /usr/bin/php5 /var/www/vhosts/example.com/streaming.example.com/index.php admin cron3 > /dev/null

One of the scripts https://www.example.com/members/send_notif should be running every five minutes but isn’t. I see there is a space before the https and i think that might be the cause. How do i edit? I haven’t got access to cpanel, so i have to do from PHP.

3

Answers


  1. Chosen as BEST ANSWER

    Found out how to do it.

    $url = " https://www.example.com";
    $new_url = "https://www.example.com";
    $output = shell_exec('crontab -l');
    $output = str_replace($url,$new_url,$output);
    file_put_contents('/tmp/crontab.txt', $output.PHP_EOL);
    echo exec('crontab /tmp/crontab.txt');
    

  2. Try something like:

    # new crontab EDIT THIS
    $crontab = '''MAILTO="[email protected]"
    */2 *   *   *   *   /usr/bin/php5 /var/www/vhosts/example.com/streaming.example.com/index.php admin cron  > /dev/null
    MAILTO=""
    */1 *   *   *   *   /opt/psa/admin/sbin/fetch_url 'https://www.example.com/referral/send_referral_email'
    MAILTO=""
    */5 *   *   *   *   /opt/psa/admin/sbin/fetch_url ' https://www.example.com/members/send_notif'
    MAILTO="[email protected]"
    */2 *   *   *   *   /usr/bin/php5 /var/www/vhosts/example.com/streaming.example.com/index.php admin cron3 > /dev/null''';
    
    # echo new cron into cron file
    shell_exec('echo "' . $crontab . '" >> mycron')
    # install new cron file
    shell_exec('crontab mycron')
    # delete cron file
    shell_exec('rm mycron')
    
    Login or Signup to reply.
  3. Once you have the output of crontab, make the required change in the variable and then write it to a file:

    $output = shell_exec('crontab -l');
    $find="' https";
    $replace="'https";
    $output =str_replace($find, $replace,$output);
    $file="/path_to_a_file_which_is_writable/crontab.txt";
    file_put_contents($file, $output);
    

    Then write the new content to crontab:

     shell_exec("crontab ".$file);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search