Search code examples
phpcronprivileges

PHP script not running with www-data cron


After a week of trying I don't know what else to do. I have a simple PHP script that is on my webserver called getpoem.php. The script opens up a website pulls its content and saves it to a poem.txt on the server

<?php
    //File to extract the Poem of the day
    $homepage = file_get_contents('http://SomeWebsite.com/today.php');
    $poemALL = substr($homepage,strpos($homepage,"<p>"),strlen($homepage));
    .
    .  // extracting the poem and saving it to $poemFinish
    .
    file_put_contents("poem.txt", $poemFinish); ?>

so this is a fairly simple script (it works fine if I manually execute it). This script should be executed with the www-data user with its cron so I opened up cron with this command and entered the command it should run

sudo crontab -u www-data -e 

0 3 * * * php /var/www/html/getpoem.php

to avoid any permission problems I gave the getpoem.php and poem.txt rwx rights like this (I know I should change it when its live but this is just to test)

-rwxrwxrwx 1 www-data www-data 1189 Aug 17 15:07 getpoem.php
-rwxrwxrwx 1 www-data www-data 1335 Aug 17 15:07 poem.txt

So this is the setup, but it will not execute.

What I did so far changing the "php" to /usr/bin/php to secure that cron know what php is. Next thing I did was making sure that cron was running so I changed the cronjob to

2 * * * */usr/bin/php /var/www/html/getpoem.php | > /var/www/html/test.txt

which again did nothing .... so I changed it to

2 * * * */usr/bin/php /var/www/html/getpoem.php | > /tmp/test.txt

that did not run the php file but created a empty (-.-") file called test.txt in my tmp dir.

So I think the problem must be somewhere in the access rights of my www-data user. It's just very weird because all my webcontent (php files, webapp usw.) are also owned by the www-data user and they run smoothly.

Do I need to grant extra privileges for the cron of www-data?


Solution

  • When running php from cron, your working directory usually isn't the directory the file is located in. When writing a file, it might try to write the file poem.txt relative to / which usually isn't writable.

    So you either set the working directory or you should use "absolute" paths. So for example:

    file_put_contents(__DIR__.'/poem.txt');
    

    where __DIR__ is a magic constant that contains the directory where the current file is in.