Article
Introducing Cron
Page: 1 2
Getting PHP and Cron to Work Together
This all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will happen (barring very special configurations that have PHP compiled as an executable, as opposed to an Apache module). The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other words, the page needs to be called via a browser or other means of retrieving Web content.
For our purposes, I’ll assume that your server configuration includes wget, as is the case with most default configurations. To test your configuration, log in to shell. If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following:
# wget --help
If you are greeted with a wget package identification, it is installed in your system.
You could execute the PHP by invoking wget on the URL to the page, like so:
# wget http://www.example.com/file.php
Now, let’s go back to the mailstock.php file we created in the first part of this article. We saved it in our document root, so it should be accessible via the Internet. Remember that we wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might have to compensate for the time difference when setting this value.
This is what my crontab will look like:
0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php
Adding the Command to Cron
Okay, so we have a text file. Now what? Now we have to add the text file bearing the crontab to the list of scheduled items. To do that, we simply need to invoke the crontab command.
# crontab stockcron
Summary
There are literally tons of things that can be done with PHP, and as many that can be performed with Cron. Hopefully this gives you a brief overview of some of the possibilities.
You can actually combine more elaborate PHP schemes into a single cron job simply by executing them via a single PHP file. As I mentioned before, it’s even possible to bypass wget by using PHP as a shell scripting language. This would require PHP to be compiled as a standalone binary, and that would bring with it a number of risks, but it can (and has!) been done.
The bottom line is that anything you can accomplish with PHP, you can likely automate with Cron. Happy coding!