Running
PHP scripts as cronjobs
I personally
found myself in the need to run some PHP scripts I wrote, every X minutes,
or evey day at a certain time and so on.
One example: phpauction
package includes a script (cron.php) which is responsable for detecting
expired auctions, close them (thus updating database tables accordingly),
sending e-mails (to the seller and eventually to the winner of the auction),
writing into a log file and more.
I use to run this script every minute in the sites where I use phpauction.
The first solution if you have such a problem would be to run the script
directly from the browser (http://www.somedomain.com/cron.php) but if
you really need and want to run your script regularly, this solution becomes
ridiculos.
A second possible approach is to include the script in one of the pages
of the site (i.e. index.php). Something like:
include "cron.php";
?>
at the very top of index.php. This works but only if someone accesses
our index.php page. Again, if you want regularity, this is not a real
solution.
Cron is usually
available in all Unix/Linux installations. It is a daemon which allow
you to schedule programs and scripts execution. If you want to read something
more about cron, go
here.
Let's suppose
you know what cron is and how it works. We now have to run (following
the cron.php sample) our script, let's say, every minute.
The first dilema depends on your PHP installation:
- Compiled
CGI
- Apache
module
Compiled
CGI
In the first case you'll have to add a line to your script. It must the
first line of your script and must contain PHP executable location:
#!/usr/local/bin/php
-q
After that
let's add the necessary command to our crontab. Edit /etc/crontab (or wherever your crontab file is) and
add the following line:
* * * * * php /path/to/your/cron.php
execute the
following from the command line:
Shell> crontab crontab
Be sure cron.php has the necessary permissions to be executable.
Apache module
If you have PHP installed as an Apache module the approach is quite different.
First of all
you need access to lynx (read here
for more information).
You PHP script does not need additional lines in this case. You simply
have to edit your /etc/crontab file and add the following line:
* * * * * lynx -dump
http://www.somedomain.com/cron.php
Note you
generally have to specify the compete URL: depending on your lynx configuration
the URL should be relative but I suggest to always use the absolute reference
like in the example above, since it always works.
Again execute
the following from the command line:
Shell> crontab crontab
That's it. |