Cob50nm
Cob50nm

Reputation: 961

Execute php file from bash script as www-data using crontab

I am trying to run a php file every night at a certain time using crontab, however the php needs to be running as a www-data because of the directory permissions. To run it as www-data I am using the root crontab and changing the user in there, like so:

* 20 * * * sudo -u www-data /usr/bin/env TERM=xterm /path/to/dailyProc.sh

dailyProc is as follows

today=`date +"%d%m%y"`

year=`date +"%y"`

dm=`date +"%m%d"`

`tar -zxf /path/to/input/$today.tgz -C /path/to/output`

echo "starting data proc"

`/usr/bin/php5 -f /path/to/dataproc.php date=$dm year=$year`

echo "data proc done"

All other commands in dailyProc.sh work but the php doesnt run. The php is using an output buffer and writing it to a file, which works fine calling it from the command line but doesnt work when calling by cron.

I can also definitely run dailyProc.sh from the command line as www-data using

sudo -u www-data dailyProc.sh

and everything works as expected.

Is there any reason I would not be able to run this php file in dailyProc.sh using crontab when everything else in it works?

Upvotes: 4

Views: 5805

Answers (4)

user7272596
user7272596

Reputation: 21

Cron can be run per user too.

crontab -u www-data -e

Upvotes: 2

Cob50nm
Cob50nm

Reputation: 961

To do this I used curl inside dailyProc.sh

today=`date +"%d%m%y"`

year=`date +"%y"`

dm=`date +"%m%d"`

`tar -zxf /path/to/input/$today.tgz -C /path/to/output`

echo "starting data proc"

`/usr/bin/curl "myserver.com/dataproc.php?date=$dm?year=$year"`

echo "data proc done"

Upvotes: 0

lxg
lxg

Reputation: 13117

You do not need to use su or sudo in a crontab entry, because the 6th column is for the user name anyway. And you don't need to start a terminal, because you won't see it anyway. Hence, the following should do:

* 20 * * * www-data /path/to/dailyProc.sh

The Syntax error: word unexpected… you mentioned in a comment appears to be inside your code. Try running the script from the command line and start debugging from there.

Upvotes: 1

Richard
Richard

Reputation: 2815

This works for me:

* 20 * * * su - www-data -C "/path/to/dailyProc.sh"

Upvotes: 1

Related Questions