Search code examples
phpcronlinode

How to execute php files with crontab in linode


I am trying to execute a php file hosted on linode with crontab.

Here's what i've done so far.

i added a line to :

/etc/crontab ('crontab -e' is used too)

And I want to execute this file every 2 mins.

*/2 * * * * /usr/bin/php /srv/www/path/to/my/php/file.php

Here's the code in my php file for testing

// Set error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
ini_set('html_errors', 'On');
ini_set('allow_url_fopen', 'On');

$fh = fopen('gallery.xml', 'w+');
fwrite($fh, $_SERVER['REQUEST_TIME']);
fclose($fh);

Both the php file and xml file are with 777 permission. If I open the php file directly in the browser, the xml file can record the variable. But nothing happen when I used the crontab. It seems that it didn't work for me.

I am using Linode and debian 6.

Am I doing anything wrong? Please give some suggestion. Thanks.

Bryant


Solution

  • You may need to correctly set your working directory or use absolute paths for your fopen() as cron's default working directory is the home directory of whatever account the job's running under, so it may be ~/root or ~/yourusername (see this stackexchange question too). You may try this:

    */2 * * * * ( cd /srv/www/path/to/my/php/ ; /usr/bin/php -q file.php )
    

    or this:

    */2 * * * * cd /srv/www/path/to/my/php/ && /usr/bin/php -q file.php
    

    and the difference is that 2nd one will not fire PHP if cd failed which is perfectly what we want as if cd failed there will be no file.php to launch.

    You can also set executable bit (i.e. chmod a+x file.php) and add this as very first line to your script:

    # /usr/bin/php -q
    

    so you'd be able to invoke your script as any other app or script (i.e. ./file.php). then your crontab entry would look:

    */2 * * * * cd /srv/www/path/to/my/php/ && ./file.php
    

    And do not use cryptic "-1" in your error_reporting(). It tells nothing. Use E_ALL or anything that ends in valid setting and is more self explanatory than -1.