Thursday, August 21, 2008

Timing out in PHP

Here is an easy way that I was able to make something disappear from a web page after a certain number of days using PHP. For example say I have a post or entry in a database that contains the date entered in MM/DD/YYYY format (02/21/1987 as an example). Also, imagine that I want that to display on the web page for 5 days and then be removed. Well I wrote a very simple function to do just that.


function timeout($date){
$curr_time = time(); //gets the current unix timestamp
$timeout = 432000; //time out in 432000 seconds or 5 days

$post_date = strtotime($date);

//if it has timed out, do not display, return false
if (($curr_time - $timeout) > $post_date){
return false;
}else{ //it has not timed out, return true
return true;
}

}


$timeout is calculated by taking 60 x 60 which produces the number of seconds in a minute. Then multiplying that value with 60 to get the number of seconds in an hour. Then multiplying that value by 24 to get the number of seconds in a day. Finally multiply the number of seconds in a day times the number of days before a timeout (in this case 5) to produce the timeout value in seconds.

You can find more information on the strtotime function here.

This solution does have some significant drawbacks however. In this situation you are forced to load extra data from the database that may never be used. In that situation there are probably more elegant ways to hide whatever you do not want to display (most likely by never pulling the date from the database in the first place). However if you are working with small amounts of data this solution can still be effective. This can probably be used for many other purposes as well. Enjoy.

Shane

No comments: