Cron is a job based scheduler used in Unix type operating systems. It allows you to schedule tasks to be run at given intervals such as scheduling a php script to run weekly, every second day, hourly, every 3 minutes, weekends, and so on.
In this article, I will show how easy it is in running a php script from cron. It will also show you how you can run a php script via a url using wget.
Running PHP Script From Cron
I will show you 3 ways on running php script from cron which are:
- Running php script via command line in cron
- Running php script via php5-cgi in cron
- Running php script remotely via website url in cron
Running a php script usually requires the php script to have execute permissions set. Running PHP script from cron is usually a matter of specifying the file and as long as the script has execute permissions (i.e. chmod +x) then all should be good. Here are three ways I have found work very well.
Running PHP Script On Command Line From Cron
In order for the script to run correctly you should add the following to your php script. The informs the bash what type of script it is executing.
#!/usr/bin/php <?php //.. your code follows here
Next we add the entry into cron.
# you could output to a file by changing /dev/null to /some/file/to/save.log */10 * * * * /home/user/scripts/updatesomething.php > /dev/null
Note we didn’t need to execute the script via php (/usr/bin/php /path/to/script.php) since we added the header to the php script.
Running php script via php5-cgi in cron
To execute the php script from cron you need to have php5-cgi installed. You can install this on Debian use “apt-get install php5-cgi” or the equivalent command for your distribution of linux.
# PHP5-CGI: execute the php script every 2 minutes and send output to /dev/null # you could output to a file by changing /dev/null to /some/file/to/save.txt */2* * * * php5-cgi -q /home/user/scripts/parselogs.php > /dev/null
Running php script via website url in cron
And lastly we will use wget from the cron to download a website url and thus, execute the url that the php script is located at. We do this in the cron to allow the url to be downloaded at set times. To use wget, you need to install it wget using “apt-get install wget” or the equivalent command for your distribution of linux.
# wget will visit the url but won't save the file. send it to /dev/null # this executes the script as if you visited the link in your browser 0 * * * * wget -O /dev/null http://www.example.com/some_cron_script.php
And there we go, your php script will be run by cron on time, every time.