Run PHP from cron

From DreamHost
Revision as of 10:08, 31 October 2011 by Rlparker (Talk | contribs) (Reverted edits by Gts3cL6yH (talk) to last revision by Microbe)

Jump to: navigation, search


One method to automatically run a PHP script at specified time intervals is to use Crontab. This can be particularly beneficial for scripts that need to automatically update information without user interaction such as a script that gathers website statistics so that they can be emailed to you or a script that regularly retrieves content from another website.

It is important to note that cron sets up a separate environment for running scripts. This environment does not include the standard environment variables your script(s) may be expecting. This means that when you create a new cron job (through the panel or manually through the shell) you must ensure that you refer to shell commands and files by their full path. This is why on the command line you can enter "php script.php" and it will work while cron requires "/usr/local/bin/php script.php" to do the same thing. For files your script references you also need to use the full path to refer to them (i.e. /home/<USER NAME>/path/to/text.txt).

Simple Cron Job

The way to have a PHP script run automatically is to make an entry in a cron file. An easy way to do this is to open your DreamHost panel and click on "Cron Jobs" under "Goodies" in the left hand menu. Click "Add New Cron Job" and then fill in the information. You will need to select a user whose account will be used to run the PHP script (this user must have shell access). Enter a title for this Cron Job and, if you want to have the output that would normally appear on the command line emailed to you, enter an email address.

Now the important part. Begin the "Command to run" text field by entering the full path of the PHP-CLI instance that you want to use to run the script. If you want to run your script using PHP 5 that path would be:


note: If you are using php 5.3 be sure to use


This informs the cron environment where to locate the necessary PHP commands. On the same line enter the full path to your PHP script. The final result of the command to run should look something like this:

/usr/local/php5/bin/php /home/<USER NAME>/path/to/script.php

Now all you need to do is choose when to have the cron job run and you're set! Click the "Add" button to have this cron job added to your account and it will take effect immediately.

See also