Tuesday, January 15, 2013

Simple cache for websites

I used to have issues with shared hosting. when you use database it will really slow your webpage. now to fix this i only fetch the data from the db once and save it as text file using cache see below:
<pre>
<?php
ob_start();
if( !isset($_GET['preview']) ){
 $uri = ($_SERVER['REQUEST_URI'] != '/')?$_SERVER['REQUEST_URI']:'index.html';

 $uri = str_replace('/','-',$uri);
 
 if( file_exists('cache/'.$uri) )
 {
  echo file_get_contents('cache/'.$uri);
  echo '<!-- im cached'.'cache/'.$uri.'    created:'.date("Y-m-d H:i:s",filemtime('cache/'.$uri)).'--!>';
  
  $date2 = strtotime(date('Y-m-d H:i:s'));
  $date1 = filemtime('cache/'.$uri);
  $diff = abs($date2 - $date1);
  $hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60));
  if( $hours > 1) unlink('cache/'.$uri);
  exit;
 }

 define('WP_USE_THEMES', true);
 require('./wp-blog-header.php');

 $content = ob_get_contents();

 if(!preg_match('/Error establishing/mis',$content)){
  file_put_contents('cache/'.$uri, $content);
 }

 
 echo '<!-- im not 2 cached--!>';
}
else{
 define('WP_USE_THEMES', true);
 require('./wp-blog-header.php');
}
echo '<!-- im not cached--!>';
?>
</pre>
the script will create a physical file and will be deleted after an hour. deleting of files is not run by cron you can do it if you want but in this case once user access the page and see's expired cached it will be deleted and create new one.

No comments:

Post a Comment