morne morne - 1 month ago 8
PHP Question

How can I write a PHP cron script?

I'm sorry if this is a silly question, but in reality I have no clue.

I wrote this app to compress and move files from a client's PC to a master PC.

It works well as a web page. This was don with little guidance and no spec doc.

So as fate would have it, it was supposed to be a cron job which would run by calling


So I don't know in which order the execution will or should take place.

I used 2 AJAX calls to call methods in the script, but just running the file as a script is n bit different.

Can anyone please guide me?

e.g. is there a MAIN method that will be called first.
and if so, then I can guide the script from there.


The answers are really help full, but how would the php file be affected? @Ole Haugset mentioned that I should adapt it so use
vars. This is done in the script already by
if ($_GET["argument"]=='runScript'){}
for instance.

So appending
to the script call should work fine?

* * * * * php /path/to/file/runScript.php runScript


There are no problems running a PHP script as a cron job. What you need to do is provide the full path in the filesystem to the script file, and use the command php to tell Linux what program to run the file with.


*/5 * * * * php /var/www/vhosts/statistikk/cron/getLastArticleFromIntranet.cron.php >> /var/www/vhosts/statistikk/cron/LOG.txt 2> /dev/null

This script will run every 5 minutes, all days of the week. Whatever the PHP-script echoes / prints out, will be stored to the LOG.txt file so that I can monitor the scripts events.

Try running just the command in your shell before putting it in the cronjobs to make sure it works.

However, you say that you normally call this script with a AJAX call. This will not be possible to do with a cronjob. I assume you use AJAX to pass along some $_POST-elements that the script needs. So what you have to do is either adapt the script to allow $argv parameters as well, and add them to the crontab job, or simply make a script which does not need any given parameters before it runs.

If you are going to adapt your script to support $argv parameters, follow the answer already existing on Stack Overflow about adding parameters to the job:

How to run a php url with parameters in cron tab


I'd just like to add to my answer as from the answer below. To edit you crontab jobs in Linux you can simply use the command crontab -e.

This is the description of each required param that needs to be filled.

*     *     *   *    *        command to be executed
-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of        month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)