48 lines
1.1 KiB
PHP
48 lines
1.1 KiB
PHP
<?php
|
|
class FileCache
|
|
{
|
|
function store( $key , $data , $ttl )
|
|
{
|
|
$h = fopen( $this -> getFileName( $key ) , 'w' );
|
|
if ( !$h )
|
|
throw new Exception( 'Could not write to cache' );
|
|
$data = base64_encode( serialize( array( time() + $ttl , $data ) ) );
|
|
if ( fwrite( $h , $data ) === false )
|
|
throw new Exception('Could not write to cache');
|
|
fclose($h);
|
|
}
|
|
|
|
private function getFileName( $key )
|
|
{
|
|
$md5 = md5( $key );
|
|
$dir = 'temp/' . $md5[0] . '/';
|
|
if ( !is_dir( $dir ) )
|
|
mkdir( $dir , 0770 , true );
|
|
return $dir . 's_cache' . $md5;
|
|
}
|
|
|
|
function fetch( $key )
|
|
{
|
|
$filename = $this -> getFileName( $key );
|
|
if ( !file_exists( $filename ) || !is_readable( $filename ) )
|
|
return false;
|
|
|
|
$data = base64_decode( file_get_contents( $filename ) );
|
|
|
|
$data = @unserialize( $data );
|
|
if ( !$data )
|
|
{
|
|
unlink($filename);
|
|
return false;
|
|
}
|
|
|
|
if ( time() > $data[0] )
|
|
{
|
|
if ( file_exists( $filename ) )
|
|
unlink( $filename );
|
|
return false;
|
|
}
|
|
return $data[1];
|
|
}
|
|
}
|
|
?>
|