Search code examples
phpubuntucroncron-task

crontab issue when using exec php script?


I am using elementaryOS (base on ubuntu)

When I run commaand line:

kn3l@kn3l:/var/www/cronjob$ 
25 15 * * * /var/www/cronjob/helloworld.php > /var/www/cronjob/cron.log

and it works for crontab with terminal command line.

BUT When I using PHP with my code like this (test.php):

-rwxrwxrwx  1 kn3l kn3l    47 Jun  6 14:59 test.php*

test.php

<?php
    $output = shell_exec('crontab -l');
    echo "<pre>$output</pre>";

I go tohttp://localhost/test.php

Why I did not see any return like the command line?

Anyone could help me?


Solution

  • You have in your user crontab the following line:

    25 15 * * * /var/www/cronjob/helloworld.php > /var/www/cronjob/cron.log
    

    in crontab it is necessary to indicate which binary is executing the script. So as hw indicates, you need to replace it to

    25 15 * * * <path to php> /var/www/cronjob/helloworld.php > /var/www/cronjob/cron.log
    

    get this <path to php> with which php.

    Regarding your test.php file, take into account that the command crontab -l is being executed by the user running the php script. That is, the user running your local server.

    I did a test:

    $ ps -ef | grep apac
    .../...
    www-data  1348  1332  0 09:50 ?        00:00:00 /usr/sbin/apache2 -k start
    

    so in my case it is www-data the user running apache.

    I added your file in /var/www:

    <?php
        $output = shell_exec('crontab -l');
        echo "<pre>$output</pre>";
    ?>
    

    And nothing appeared while executing it. Why? Because www-data has no crontab:

    $ sudo crontab -l -u www-data
    no crontab for www-data
    

    I added a line:

    $ sudo crontab -l -u www-data
    * * * * * touch /tmp/tt
    

    and now the php page shows:

    * * * * * touch /tmp/tt
    

    To sum up

    The thing is not that your script is not working properly, is just that is showing an empty content as the crontab for user www-data is empty.