3

This question already has an answer here:

I have a php script that connects to an external API returns some data and updates a database table. I can run this directly via my command line / SSH terminal and it works fine (takes about 5 minutes to complete).

Using crontab I have 'cronned' this script so it runs every three hours using the command below:

0 */3 * * * /usr/bin/php /var/acme/cron/api_update_db.php

Using the syslog I can see that this cron has run, but it would appear that the cron is actually running every three hours as expected however the database doesn't appear to have been updated? But when I run the exact same script manually myself by navigating to that directory & entering the following it runs (and updates the DB)

php api_update_db.php

Would there be a reason for this executing differently when running from the cron job then when run manually from the terminal (which appears to work).

marked as duplicate by Iain linux Feb 3 '16 at 22:34

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    If you use any system() calls inside your php script then you need to provide absolute path to binaries you are calling. – user1700494 Feb 3 '16 at 16:19
  • Not really enough information to solve the problem: What is happens if you run the script without navigating to the directory first? Are you running as the same user in cron as you are outside of cron? Are there any logs that are giving you information about what is going on? – Catherine MacInnes Feb 3 '16 at 17:55
4

You may be getting some stderr\stdout output which might help identify the problem. Usually this ends up being mailed to yourself, but if not try adding specific redirection of all output to the end of your crontab entry to a file, e.g.:

0 */3 * * * /usr/bin/php /var/acme/cron/api_update_db.php &> /tmp/cron.output
3
crontab -u <username> -e 

The short answer, run the cron as a user with the appropriate credentials to the database. Source

1

Depending on the cron version/type you are using, the output from the command usually gets sent via email to someone. In the traditional style you can put

MAILTO=your.login

or maybe even

MAILTO=your_email@example.com

and get the output from the script.

In the worst case try

0 */3 * * * /usr/bin/php /var/acme/cron/api_update_db.php > /tmp/cron.output 2> /tmp/cron.error

Using &> probably won't work as well - cron executes using /bin/sh which is likely not bash and &> is not in POSIX standard, it's a bash extension (possibly taken over also by other shells, but not all of them).

Another thing to look for is that this gets executed without any of your environment variables etc. So if you have credentials for DB set as environment variable in .bashrc than this won't work.

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