Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

php

cron

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?

like image 703
Cob50nm Avatar asked Sep 03 '25 04:09

Cob50nm


2 Answers

Cron can be run per user too.

crontab -u www-data -e
like image 170
user7272596 Avatar answered Sep 05 '25 01:09

user7272596


This works for me:

* 20 * * * su - www-data -C "/path/to/dailyProc.sh"
like image 45
Richard Avatar answered Sep 05 '25 01:09

Richard