This article explain how to use only one PHP file for start several cron job in other PHP files.
The code below is useful for:
- who has shared hosting services with only one cron job activable;
- who doesn’t want to use or doesn’t want to have full access to the server crontab/cronjob;
- who is curious about the article :-).
Introduction
This is the sample environment solved:
- A cronjob is active every hours and runs mainCron.php file;
- there are fileCron1.php that will start at 02:00() and fileCron2.php will start at 23:00 ();
- fileCron1 and 2 are in a directory accessible from a public url, there is an expedient to prevent improper use of these.
PHP code
define("PROTECTION","1"); startCron('fileCron1','02'); //will start the fileCron1.php file at 02:00 startCron('fileCron2','23'); //will start the fileCron2.php file at 23:00 function startCron($op,$time){ $Hnow = date('H'); //get actual hour if ($Hnow >= $time && $Hnow < ($time+1)){require($op.'.php');} }
the define SECRET statement will prevent the public access to the 2 fileCron PHP, but is necessary a line of code inside both files in the first line of code, after the php open tag (<?php) like that:
if (!isset(PROTECTION)){exit;}
for adding a cron file is possible to use the startCron function: startCron(phpFilename, HH);
The code above is a good start also for a more precise cron, it will be easy to add minutes and seconds control.