Fer
Fer

Reputation: 4196

Cannot get PHP cron script to run

I have a PHP script that I need to run every minute. I have made sure that the script works from the command line, and I'm using absolute paths to avoid any environment issues:

/usr/bin/php -q /var/www/myapp/services/myservice.php

Manually running that as root from the command line works fine, as I can see from the log file that my script writes to. To be sure, the script has execute permissions as well.

However, when placing the same exact command in a cron:

* * * * * /usr/bin/php -q /var/www/myapp/services/myservice.php

It does not run or at least it appear so. I've tried redirecting the output to another log file too:

* * * * * /usr/bin/php -q /var/www/myapp/services/myservice.php >> /mylog.log 2>&1

Still nothing. I have no indication whatsoever of the script being ran. I guess it doesn't, but I have no idea what else to look for. I even restarted the cron daemon.

I know there are similar questions on StackOverflow, but none of the answers turned out to be a solution for me. This is literally driving me crazy, I will greatly appreciate any help.

Upvotes: 2

Views: 4227

Answers (4)

ariefbayu
ariefbayu

Reputation: 21979

you missed the running user section:

* * * * * nobody  /usr/bin/php -q /var/www/myapp/services/myservice.php >> /mylog.log 2>&1

Upvotes: 1

user15063
user15063

Reputation:

This might be considered "bad practice" but it works for me.

Run it with curl

* * * * * curl -s http://www.domain.com/services/myservice.php

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881443

There are usually a significant number of things you need to do to move an executable from the command line to a cron job.

By default, cron jobs get a minimal environment which will almost certainly not have the full path (and a host of other environment variables) that your login sessions have. You may also not be in the same directory (as you have discovered).

What I tend to do is to execute:

env | sed 's/^/export /' >$HOME/cron.env

from a login session to get the full environment, then make sure that my cron jobs execute that script before attempting to do the real work. The resultant script may need a small amount of tidying up (quoting, removing transient environment variables like _ and PWD and so forth).

That way I can be sure that the login and cron environments are identical.

Upvotes: 1

Fer
Fer

Reputation: 4196

I found a solution for my issue:

https://serverfault.com/questions/97828/php-from-command-line-path-problems/97881#97881

It turns out I needed to cd (change directory) into the script dir and then call it. Surprising, since I'm using absolute paths, but it works. Thanks to those who have taken the time to respond.

Upvotes: 2

Related Questions