Hello ;
I am trying to cache part of a php page, the part of the php page is in the header. Whenever I run it the first time, page displays correctly. However when I run it for a second time , reading from cache file, the php page breaks down after displaying the cache file. What am I doing wrong, is this because of the fclose () ?
<?php
class cache
{
var $cache_dir = './cachemenu/';//This is the directory where the cache files will be stored;
var $cache_time = 1000;//How much time will keep the cache files in seconds.
var $caching = false;
var $file = '';
function cache()
{
//Constructor of the class
$this->file = $this->cache_dir . md5($_SERVER['REQUEST_URI']);
if ( file_exists ( $this->file ) && ( fileatime ( $this->file ) + $this->cache_time ) > time() )
{
//Grab the cache:
$handle = fopen( $this->file , "r");
do {
$data = fread($handle, 8192);
if (strlen($data) == 0) {
break;
}
echo $data;
} while (true);
fclose($handle);
exit();
}
else
{
//create cache :
$this->caching = true;
ob_start();
}
}
function close()
{
//You should have this at the end of each page
if ( $this->caching )
{
//You were caching the contents so display them, and write the cache file
$data = ob_get_clean();
echo $data;
$fp = fopen( $this->file , 'w' );
fwrite ( $fp , $data );
fclose ( $fp );
}
}
}
?>
I i include the file in the pages where I want to use it and run it on the specific page with
<?php $ch = new cache(); ?>
//Content goes here
<?php $ch->close(); ?>
What am I doing wrong ?
Thanks;
Pascal