Nginx – How to PHP to set up a crontab job that runs as www-data

cronnginxubuntu-14.04

My server is running on Ubuntu 14.04 and nginx. My problem concerns Cron, I'd like to start it (crontab) using a file – cron.txt, its contents:

* * * * * /usr/bin/php /var/www/html/test.php >> /var/log/cron.log

If I run it using the command: crontab /var/www/html/cron.txt, it works perfectly, script test.php is being executed. But, when I do the same using a PHP script (executing via browser): exec('crontab /var/www/html/cron.txt');, it doesn't work.

Checking current cronjob by command: crontab -l -u www-data, the line from the file appears, but Cron does not do its job. Maybe it's related to some permission issues? Because it only works by executing as a root. Is there a way to force Cron to do www-data's tasks as well?

Best Answer

I do not clearly understand what are you trying to achieve. As far as I understand you need to execute a cron job as www-data user. Usually (is highly recommended) www-data user does not have access to shell. But you can execute cron tasks as www-data, placing your tasks in the root cron as follows:

* * * * * su www-data -s /bin/bash -c "/usr/bin/php /YOUR_PATH/task.php"

This is also a clean way, as you have all the cron jobs of the system centralized in one file, but each tasks runs as the needed user (with the proper permissions and attributes).

You can change the * * * * parameters in order to adjust the schedule of your job. In my example it runs every one minute.

Hope it helps.