August 2009

Assuming you have a web host that allows you to setup cron jobs (therefore it's a Linux/UNIX based server), and you know how to do it, you can run pretty much any PHP script as a cron job. Cron is a UNIX tool that allows you to run a certain commands at pre-defined times.

One of the key elements to getting PHP to work as a cron is to tell it how to deal with the PHP script. As cron is a feature of UNIX (the operating system), and therefore outside of Apache (the web server software) the file extension .PHP means nothing at all. Therefore we must tell UNIX what to use to process that PHP code.

If you know enough about your PHP configuration, then you probably know how to tell a program where PHP is installed. If you have no idea, it's very simple to find out where PHP is on your server.

Simply create a new PHP file, and call it something sensible like phpinfo.php, and upload it to somewhere password protected on your web server (the information this file will contain would be very handy to any hackers hoping to exploit your contact form or members area for example)

Then edit that file to contain simply the following PHP function:


Point your browser to your new PHP file and you will get a page containing a huge amount of information about your PHP installation. You're looking for something like "PATH: /usr/local/bin", which is the location of PHP on your server. If you don't see anything, you get an error message, or you see the contents of the PHP script, contact your web host and ask them if you have PHP installed.

Assuming you are familiar with cron and how to set it up (if not have a look at this wikipedia entry) you then need to create a cron tab that looks something like this:

* * * * * /usr/local/bin/php www/phpscript.php

This will run phpscript.php every minute of every day until the webserver crashes or is destroyed by nuclear war.

The important parts, the bits that many people get wrong are the path to PHP and the path to the PHP script. Your path to PHP may be different to /usr/local/bin, but phpinfo() should tell you exactly where it is. And the path to the PHP script needs to be relative to the home directory of your website.

And once you get it all working, remember to change the frequency of the cron to once a day or something reasonable (depending on what you are asking it to do). Once a minute might knacker your server.