Greg
Greg

Reputation: 7922

PHP Cronjob -- permission denied?

So, I set up a cronjob to run the following command:

php /var/www/path/to/cron/do-stuff.php

The path is correct. The directory is owned by www-data.

The script does the following:

chdir( getcwd() );
echo shell_exec('whoami');

$handle = fopen(uniqid('TEST_') . '.tst');
fwrite($handle, 'foo');
fclose($handle);

This is the output I get when trying to run the cron job:

www-data
PHP Warning:  fopen(TEST_4e15266d09fa2.tst): failed to open stream: Permission denied

Yet when doing this from shell with su www-data -- the script executes just fine and produces the test file without a hiccup.

Any idea why this might be?

EDIT: I guess the su www-data is probably unnecessary, because php will run however it runs, but I tried that just in case. The cron and script is executed as www-data though, as you can see from the output.

Upvotes: 2

Views: 5811

Answers (3)

fabbricasiti
fabbricasiti

Reputation: 21

The cron job handles PATH in a quite different way. The same script that usually works when it is called from the command line could return a permission error like this when it is called from crontab if you don't specify the PATH.

Try to change the line:

$handle = fopen(uniqid('TEST_') . '.tst');

in something like this:

$handle = fopen('/var/www/vhosts/yourpath/'.uniqid('TEST_') . '.tst');

It worked for me.

Upvotes: 2

fanfavorite
fanfavorite

Reputation: 5199

Have you tried putting the full path in the fopen function instead of just the filename?

Upvotes: 5

arkigos
arkigos

Reputation: 362

I am confident that even though this is in a cron, PHP itself still runs as it's default user (what that is can vary, of course) and this cannot reasonably be changed. I may be wrong. Try grouping the directory to the PHP system user (apache?) and giving group write permissions. Then see if that works.

Upvotes: 0

Related Questions