Running PHP File under Crontab...

Nerius Landys nlandys at gmail.com
Sun Jan 17 20:01:49 UTC 2010


> I am wanting to execute a PHP file 5 times a day via crontab. Is it
> possible?  If so what is the proper crontab command for this?

Hi.  I'm running several PHP programs via cron.


#1 Make sure you have CLI (command line interface) in your PHP port:

As root,

> cd /usr/ports/lang/php5
> make config
Then make sure the "CLI" is set to "on".  If it isn't, change it, and
recompile the port.  For example "portupgrade -f php5-5.2.12" will
recompile the port, if you have portupgrade installed.


#2 Write the PHP script you want to run.  There are different syntaxes
for writing a command-line PHP program but here is one of them:


<?php
// Your PHP code here
?>


Save this to a path "/path/to/mycode.php".


#3 Add cron job to execute this program.

Your crontab should look like this:

*/5 * * * * /usr/local/bin/php -f /path/to/mycode.php

(That would execute your PHP script every 5 minutes for example.)



That's it!

There is an alternate way to write PHP scripts for CLI, but I have not
used it extensively, so I don't know all the details or the correctest
way to do it.

You can write a script like this:

#!/usr/local/bin/php
<?php
echo "Hello!\n";
?>

And then save it to a file for example "test.php" and set the
executable permission on it.  Then you can just:

./test.php

from a terminal.  So you could change the cron to just execute the
script directly in this case instead of explicitly calling
/usr/local/bin/php in the crontab.


More information about the freebsd-questions mailing list