Run Function every Night

You can run a file once a day triggered by the first time the page is loaded for that day. I’ve used a version of this on several projects where clients don’t have a clue how to setup a cron job for their site.

There are two parts,

crontab.php - the file that holds the last date the script was run.
fakecron.php - the page that controls everything. Note: files you wish to run are put in an array so you could have several run, sending emails etc.

I would suggest having both these files in your base directory as well as any files you wish to run.
The file fakecron.php should be included only on your primary index.php page.

include "fakecron.php";

crontab.php

<?php

// Set $lastrun = "never" to stop fakecon from running completely

$lastrun = "2014-08-02";

?>

fakecron.php

<?php
// Name of crontab file
$crontab = "crontab.php";
// List files to run
$jobs = array("myfile.php");
// Double check that file exists
if (file_exists($crontab)):
	include_once "$crontab";
	if (isset($lastrun)):
		if ($lastrun == "never") $error="true";
		if ($lastrun == date("Y-m-d"))  $error="true";
		if ($lastrun != date("Y-m-d") && $lastrun != "never" && !isset($error)):
		
			$ran = 0;
			foreach ($jobs as $job):
				if (file_exists($job)):
					include "$job";
					$ran++;
				endif;
			endforeach;
			
			// update crontab file
			if($ran != 0):
				$CTcontent = "<?php\
\\r\
\\r";
				$CTcontent .= '// Set $lastrun = "never" to stop fakecon from running completely'."\
\\r\
\\r";
				$CTcontent .='$lastrun = "'.date("Y-m-d")."\\";\
\\r\
\\r?>";
				if (is_writable($crontab)):
					$handle = fopen($crontab, "w");
					if (fwrite($handle, $CTcontent) === FALSE):
						// echo only while testing
						//echo  'Fake Cron error! Could not write to '.$crontab.".\
";
						//exit;
					endif;
					fclose($handle);
				endif;					
			endif;			
		endif;
	endif; 
endif;
?>

Note while testing you’ll need to keep editing crontab.php setting the date to yesterday but you’ll need to NOT have crontab.php open in an editor so it can be written to by the script. Learned that the hard way.