How to run crontab as user:www-data?

Solution 1:

You can also run crontab with the -u argument to edit a crontab for a specific user:

sudo crontab -u www-data -e

Solution 2:

You can write your entry into the system crontab /etc/crontab, which takes an additional argument specifying the user to run as (usually root, but can be www-data).

Your line would become:

*/5 * * * * www-data php /var/www/public/voto_m/artisan top >/dev/null 2>&1

Or you can edit the crontab of user www-data with su:

sudo su -c "crontab -e" www-data -s /bin/bash

Solution 3:

To run a crontab as user www-data you can use the following command:

crontab -u www-data -e

Then you write a line, for example to run a php file every 15 minutes:

*/15  *  *  *  * php -f /path_to_cron/cron.php

When saving it, you will be asked by the editor:

File Name to Write: /tmp/crontab.HMpG7V 

Save it there, no worries. crontab -e opens a file in /tmp instead of the actual crontab so that it can check your new crontab for errors and prevent you from overwriting your actual crontab with those errors. If there are no errors, then your actual crontab will be updated. If crontab -e just wrote straight to your actual crontab, then you would risk blowing away your entire crontab.

To verify that your cronjob runs, you can check the cron logs. typically in /var/log/cron.log or executing the following command:

crontab -u www-data -l