Here I will show you how to create a cron job using PHP. This function will write a cron file to your folder under the proper user and group automatically and will allow you to use it more than once in a script. This is good for when you want to set the cron to specific times according to your script.
For example, I have a script that pings a FTP server every hour. If a file appears during this ping called “inprocess.txt” I want to change the ping to 5 minutes. Then when the file is gone I want to run my script and reset the ping to every hour.
This function does just that:
First create a folder called cron and chmod it to 777
function crontab_set ($min, $hour, $monthDay, $monthNum, $weekDay){ $command = "$min $hour $monthDay $monthNum $weekDay /usr/bin/php -f /full/path/to/pinger.php"; $cron_file = "/full/path/to/cron/Feed_cron"; // check for Feed_cron file. If it doesn't exist create it. // you must create the file from the browser to associate the proper group if (file_exists($cron_file)){ // if it exists, write new command $open = fopen($cron_file, "w"); // This overwrites current line fwrite($open, $command); fclose($open); // this will reinstate your Cron job exec("crontab /full/path/to/cron/Feed_cron"); } else { // if it Doesn't exist, Create it then write command touch($cron_file); // create the file, Directory "cron" must be writeable chmod($cron_file, 0777); // make new file writeable $open = fopen($cron_file, "w"); fwrite($open, $command); fclose($open); // start the cron job! exec("crontab /full/path/to/cron/Feed_cron"); } }
That is it! Now when we call the function for any variable that is not needed in the time for the cron we enter “*”. For example, if we want this script to run every hour we enter
crontab_set ("60", "*", "*", "*", "*")
Also don't forget the -f option, which tells PHP you are parsing a file. If this still doesn't work check the script in Line Command (bash# usr/bin/php -f /Users/vin/Sites/site/pinger.php ). If you receive an error here your cron will not process. Some times cURL can be installed in the apache module and not the PHP application and can cause your crons to fail since Cron is not an apache module but a system command. It is also important to make sure your files are executable (chmod 755 file.php).