Sunday, August 8, 2010

PHP Scripts With Cron

You will need to find out the answer to the following question, “Is my PHP installed as CGI or as an Apache module?”. To find out do the following: Create a new file, name it info.php (just an example), and put in the following code:
< ? phpinfo(); ? >
Upload to your webserver and go to it with your browser.
Now check for Server API (4th item from the top), if it says “CGI”, you have PHP compiled as CGI, if it reads “Apache”, you have it running as an Apache module.

Compiled CGI

If the answer to the question above is “CGI” then you need to add a line to your PHP script. It has to be the first line of your script and must contain your server’s PHP executable location:
#!/usr/local/bin/php -q
That looks a lot like PERL now, doesn’t it? After that let’s add the necessary command to our crontab. Edit /etc/crontab and add the following line:
* * * * * php /path/to/your/cron.php
Execute the following from the command line:
Shell> crontab crontab
Be sure your “script.php” has the necessary permissions to be executable (“chmod 755 script.php”).
Now you are all set!

Apache module

If your PHP is installed using the Apache module, the approach is a little different. First, you need access to Lynx (Lynx Browser for more information). Lynx is a small web browser, generally available on Unix and Linux.
Running your PHP script will not require you to add any additional lines. You simply have to edit your /etc/crontab file and add the following line:
* * * * * lynx -dump http://www.somedomain.com/cron.php
(or if email notification is not needed:
*/15 * * * * lynx -dump http://www.somedomain.com/cron.php >/dev/null 2>&1 )
Please note that in general, you have to specify the entire URL (with “http://” and so on). But depending on your Lynx’s configuration, the URL might be relative; I suggest always using the absolute reference as in my example above – it always works.
Again execute the following from the command line:
Shell> crontab crontab