Using a cron job to run a PHP script is very easy if you know how. If we recall, cron is a Unix/Linux utility that is used to perform tasks at specified intervals. By setting up a cron job with the appropriate parameters, we can get our system to execute PHP scripts or any other kind of script.
We know that PHP scripts are usually executed by the web server, but what we might not readily realise is that the PHP interpreter is a binary file somewhere on disk. We can run the PHP interpreter from a terminal just as we run any other command. By invoking the PHP interpreter and passing the name of the PHP file to execute, we are able to execute PHP files without the need of a web server.
This technique of invoking the interpreter directly is what we will use below to have cron run a PHP script.
Though not required, it is a good idea to use the exact path to the PHP interpreter when invoking it from cron. To find the path to the PHP interpreter, run the following command in a terminal:
which phpThe system will respond with something like:
That is the path to the PHP interpreter. We will now need to add the actual cron job to the system.
Open up the crontab for editing by running:
crontab -eAdd a line like:
The above cron job will run the PHP script at /path/to/php/file at 8:30AM every day.
Take care to replace /usr/bin/php with the path to your PHP interpreter. This is the default path on Ubuntu 10. You will also need to replace /path/to/php/file with the path to the PHP file you want to execute.
For example, if you want to send an email using a PHP script, you can use the Send email using PHP script and then invoke it via cron.
Trivially, if you have the PHP script under the document root of a web server, you may run the PHP script using the web server itself, without invoking the PHP interpreter directly.
This time we would use wget, a simple utility which is used to fetch web pages. To do it this way we would use:
The above cron job will run the PHP script at http://www.example.com/script.php at 8:30AM on Saturdays.
What we have done is request the PHP script in the same way we would have requested another web page. Since the server is configured to run PHP scripts (or else it won't work) it will invoked the PHP interpreter for us which will in turn execute the script. And bingo, you're done.
So as you can see, it is very easy to use a cron job to run a PHP script. We hope this tutorial has been helpful. Check out the other articles you may like below, you just may find something else that interests you.