I have Ubuntu 14, and want to create some cron jobs using my PHP code.
Currently, I am doing something like crontab -u www-data
, and from my PHP code I am able to write into crontab.
If I do crontab -u www-data -e
I can see there are some commands, but these command are not being executed, though if I add the same commands to crontab -e
(without specifying user), they run successfully.
Cron files also have MANDATORY new-line at the end.
TL;DR:
How can I make work cron jobs created by user www-data
work?
EDIT: 1
SOLUTION: click to see solution
Best Answer
Cron will run the www.data items. You can verify this with this simple test:
Add this entry:
Now examine the output with:
After you have done that to ensure your crontab is working you can work the actual scripts you want to run.
the user
www-data
while not have the same path as you, so lots of commands that work from your account will not work from thewww-data
user unless you specifically set the path for that script. www-data's default path contains only:PATH=/usr/bin:/bin
You can do this by exporting your path list, then placing it in a path list for the script.
You can do this with:
Now append the text of the ~/mypath.txt to the top of your script as:
Your script:
You can fine tune the path by removing some obvious items that you won't be using such as in the case of my example:
That would leave the path line with of the script with:
PHP script run in cron
The php test script (
/home/users/l/j/ljames/test.php
)The php crontab entry
You can examine the output with:
The output verifies that crontab will run your php scripts. It shows that the culprit is the actual script, which would have to be debugged to function properly outside of cron first. The likely culprit would the path list of the environment.
Note:
Your sytsem with your web server scripts run as user
www-data
will be more secure than if they were run-as you or root. If they were as you, the script would have access to every thing that you have access to and if your web server were compromised it might even have root access withsudo
. Having your web server scripts run-aswww-data
, a compromised server will only be able to access your server. Which, if backed up, would be easier to fix than to have to deal with your whole server.