How to execute PHP with cron

Posted by admin on December-11-2009 Add Comments

Bookmark and Share


How to execute PHP with cron

Every now and then you will run across a task that needs to be executed through PHP however this task cannot or should not be ran by a visitor opening a webpage (such as a maintanance or caching script). The only way to run these scripts would be to do it manually as an administrator or to do it automatically using cron.
Manually sucks which is why I wrote this tutorial. Specifically this will target users of cPanel installations (gotta love shared hosting). All cPanel installs that I have used have cron as an option. When you log into cPanel there should be an option called crontab or Cron Jobs or any other such thing. Clicking this option brings up the cron jobs window.
On my install I am given the choice between Standard and Advanced (Unix Style) Cron settings. Standard makes the task more easier and offers the same amount of control, so lets press Standard.
You are given two sections to enter a cron job. If you need more, just fill in the first two and more will become visible when you save your settings. You can set all sorts of options concerning when the script will run. You can run it from every minute to ever year, controling what times down to the second that the script is executed.
The command that you run is the fun part. In my install I enter the absolute path to the script (/home/ACCOUNT/public_html/script.php). Inside of the script I have added the line:

Code:
#!/usr/bin/php -q

This will run php in command line mode when the script is run (you may need to change the path to your PHP binary). Finally, you will need to chmod 755 your php file so that it can be executed.
And there you have it. Your script will be run automatically. If you don’t want the script to be executed by a person by typing in the URL, drop it into a folder and change .htaccess settings to nobody can open the file. While debugging your script (and even making sure that it is ran at all) you may want to have output saved to a log file and execute the script manually.

Post a Comment

You must be logged in to post a comment.