3

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

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

If I run it using a command: crontab /var/www/html/cron.txt, it works perfectly, script test.php is being executed. But when I do the same but 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?

3

Please use /etc/crontab. That method of doing cron jobs allows you to add a user name to the task. It will look like this:

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

You can do nano /etc/crontab and add the line to the file.

But when I do the same but using a PHP script (executing via browser): exec('crontab /var/www/html/cron.txt');, it doesn't work.

If that does not work you probably have another problem than "crontab" usage. For instance: do you not need to redirect? (ie. use > /dev/null 2>/dev/null & at the end of your exec command?).

  • Awww, you beat me to the actual answer. Mine was a comment, but your's much better! +1 =) – Terrance Jun 6 '17 at 19:15
  • @Terrance been there done that ;=) – Rinzwind Jun 6 '17 at 19:16
  • Honestly speaking I don't know what it means (> /dev/null 2>/dev/null &), could you explain a little? You mean something like that: exec('crontab /var/www/html/cron.txt > /dev/null 2>/dev/null &');? – BociucH Jun 6 '17 at 19:36
  • That would redirect output and errors to "/dev/null". And the "&" detaches the command from the original thread. You really should know about these though. – Rinzwind Jun 6 '17 at 20:20
0

I managed to achieve what I wanted, everything about the code in my initial post is ok, the only thing I should've known is that the www-data user is not allowed to write in /var/log, so I had no output there. And in addition, in my PHP script I was trying to create a file and write something into it, to do is, the absolute path is required, so it should look like:

dirname(__FILE__) . '/myfile.txt';

After these changes, everything works as expected.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.