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.
Have you tried putting the full path in the fopen function instead of just the filename?