1
Votes

Simple PHP Caching and Content Retrieval Function

Posted By tamilsolai on Jun 23, 2010   FROM: advancedphptutorial.blogspot.com report abuse

PHP Caching, Content Retrieval Function

One way to make your website exponentially faster is by caching both remote and internal requests. Why request your RSS subscriber count from FeedBurner more than once a day if that count is calculated once per day? Why hit your database on each page load if that content rarely changes?

I’ve created a primitive request-and-cache function for PHP that checks for fresh content in the cache and retrieves content from a source if fresh content isn’t available.

/* gets the contents of a file if it exists, otherwise grabs and caches */
function get_content($file,$url,$hours = 24,$fn = '',$fn_args = '') {
//vars
$current_time = time(); $expire_time = $hours * 60 * 60; $file_time = filemtime($file);
//decisions, decisions
if(file_exists($file) && ($current_time - $expire_time < $file_time)) {
//echo 'returning from cached file';
return file_get_contents($file);
}
else {
$content = get_url($url);
if($fn) { $content = $fn($content,$fn_args); }
$content.= '';
file_put_contents($file,$content);
//echo 'retrieved fresh from '.$url.':: '.$content;
return $content;
}
}

/* gets content from a URL via curl */
function get_url($url) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}

My get_content function accepts four arguments:
The file to grab content from. If the file doesn’t exist, the file is created and content placed into.
The URL to get content from if cached content isn’t fresh.
A function name to pass the freshly received content to.
Arguments to pass to the third argument’s function.
The function is, of course, very primitive. I like that my function handles both retrieval and caching so that I don’t need to repeat code whenever I want cached content.

Read Full Story from advancedphptutorial.blogspot.com

Post new comment

  • Allowed HTML tags: <a> <strong> <ul> <ol> <li> <table> <tr> <td> <tbody> <embed> <object> <param> <b> <p> <i> <div> <h3> <h4> <br> <img> <style>
  • Lines and paragraphs break automatically.

More information about formatting options