Time Delay Content by File Access Time

I was working on a mini-script to display the results of a database and then log the results into a log file. One of the problems with the logging script was that every time the page was displayed, it would pull the results from the database and log the results.

I needed a way to prevent a user from accessing the update script randomly but also needed to be able to display the update button (which linked to the update script) once a full day had passed so that the result could be manually updated in the event that they became out of date (maybe due to a failed cron job, or if a user cannot create cron jobs).

The outcome was a small script which gets the last accessed time of a file (in this case, update.php) and subtracts it from todays date and time (using the timestamp). It then determines if the resulting difference is greater or less than a certain period (in this case, 24 hours or 86400 seconds).

If the difference of time (between todays date and file) is greater than a whole day (86400 seconds) it displays the update link, because it would be good to get fresh results for that day. If, however, the time difference is less than a whole day it does not display the link or alternative content.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
	// time check
	function timeCheck(){	
		$format = 'd-m-Y H:i:s'; // time format
		$timestamp = date(time()); // current timestamp
		$day = 86400; // 86400 seconds in a day
		$file = fileatime('update.php'); // timestamp of files access time	
		$file_date = date($format, $file); // date of file	
		$today = date($format, time()); // todays date
		$difference = $timestamp - $file; // calculate the difference between timestamps
 
		if($difference >= $day){
			// if a full day has passed...				
		}elseif($difference < $day){
			// if a full day has not passed...
		}else{
			// catch all...
		}	
 
	}
?>

I will try and do a line-by-line explanation, if required but I think the script is pretty simple. If you have any points for improvement – feel free to post them here.

Post a Comment

Wrap code blocks with <pre lang="LANGUAGE" line="1"> and </pre> where LANGUAGE is a GeSHi supported language syntax. The line attribute is optional. More help here.

Your email is never shared. Required fields are marked *

*
*