Using Cron to trigger PHP scripts on Hostmonster

Author: David J McClelland

23Jan

Here is how I run PHP scripts from Cron. This should be easy, but there are a lot of details and fragmentary information.

Before jumping on Cron I made sure I had a script that works, and that would tell me when it ran successfully. I Googled for a php script that sends an email and set it to my address. I named it “sendMail.php” and ftp’d the file to my project directory.

I opened an ssh session using Putty and ran the php. This helped me determine the exact path I needed to use in cron to trigger the script.

I opened the Hostmonster cPanel and set up a script to run once every minute and entered the path to the script file. I also put in my email address in the Cron Email field to get debug and confirmation. To turn this off, click the Update Email button with the field empty.

The Cron email was handy because it told me that the php file path alone doesn’t work because Cron doesn’t know we want to interpret our file as php. It thinks everything must be a shell script (*.sh)Â no matter what file extension you use.

I thought I would have to write a shell script to tell php to run the php script – but fortunately that is not the case. I was able to find a helpful post that spells out the necessary directive to tell Cron that you wish to use PHP on the script. Quoting Michael Lueck:

“Because I want to run a PHP script, I called PHP through the shell with â€˜/ramdisk/bin/php5?. Alternatively, I couldâ€™ve used [and have successfully] â€˜phpâ€™ and â€˜/usr/bin/phpâ€™, but HostMonster seems to prefer â€˜/ramdisk/bin/php5?.”

Here is the final script (substitute site specific path elements where I have “my*”):