GEnGEr GEnGEr - 1 year ago 85
PHP Question

Php script not running with www-data cron

after a week of trying i dont 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

//File to extract the Poem of the day
$homepage = file_get_contents('');
$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 opend 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 shure that cron was running so i changed the cronjob to

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

wich 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 someware in the acces rights of my www-data user. It's just very wierd because all my webcontent (php files, webapp usw.) are also owned by the www-data user and they run smoothly.

Do i need to grand extra privileges for the cron of www-data ?

Answer Source

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:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download