Skip to content

Instantly share code, notes, and snippets.

@yetimdasturchi
Created July 14, 2023 13:39
Show Gist options
  • Save yetimdasturchi/f20e77d31f661caf0e669b7ad8d1134d to your computer and use it in GitHub Desktop.
Save yetimdasturchi/f20e77d31f661caf0e669b7ad8d1134d to your computer and use it in GitHub Desktop.
Simple cache system in php
<?php
function write_file( $path, $data, $mode = 'wb') {
if ( ! $fp = @fopen( $path, $mode ) ) return FALSE;
flock( $fp, LOCK_EX );
for ( $result = $written = 0, $length = strlen( $data ); $written < $length; $written += $result ) {
if ( ( $result = fwrite( $fp, substr( $data, $written ) ) ) === FALSE ) break;
}
flock( $fp, LOCK_UN );
fclose( $fp );
return is_int( $result );
}
function read_file( $file ) {
return @file_get_contents( $file );
}
function delete_files( $path, $del_dir = FALSE, $htdocs = FALSE, $_level = 0 ) {
$path = rtrim($path, '/\\');
if ( ! $current_dir = @opendir( $path ) ) return FALSE;
while ( FALSE !== ( $filename = @readdir( $current_dir ) ) ) {
if ( $filename !== '.' && $filename !== '..' ) {
$filepath = $path.DIRECTORY_SEPARATOR.$filename;
if ( is_dir( $filepath ) && $filename[0] !== '.' && ! is_link( $filepath ) ) {
delete_files( $filepath, $del_dir, $htdocs, $_level + 1 );
}elseif ($htdocs !== TRUE OR ! preg_match( '/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename ) ) {
@unlink( $filepath );
}
}
}
closedir( $current_dir );
return ( $del_dir === TRUE && $_level > 0 )
? @rmdir($path)
: TRUE;
}
function cache_get($id=NULL, $expire = FALSE ) {
if ( empty($id) ) return FALSE;
$path = cache_path( $id );
if (file_exists( $path )){
if ( !$expire ) $expire = 300;
if (time() - filemtime($path) < $expire ) return read_file( $path );
@unlink( $path );
}
return FALSE;
}
function cache_save($id, $data) {
if ( empty($id) ) return FALSE;
if (write_file( cache_path( $id ), $data ) ) {
chmod( cache_path( $id ), 0640 );
return TRUE;
}
return FALSE;
}
function cache_delete($id) {
$path = cache_path( $id );
return is_file( cache_path( $id ) ) ? unlink( $path ) : FALSE;
}
function clear_cache() {
return delete_files( cache_path(), FALSE, TRUE );
}
function cache_path( $file='' ) {
$path = config_item( 'cache', 'path');
$path = ( $path === '' ) ? '/tmp/' : $path;
return ( $file === '' ) ? $path : $path.$file.'.cache';
}
if ( ! $foo = cache_get('foo', 60)) {
$foo = 'bar';
cache_save('foo', $foo);
}
echo $foo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment