Wednesday, August 28, 2013

how to create dynamic cache file using php[Solved]

Hey guys you can do your own cache file using php simple function you can learn :)
getUrl() function  identify the specific  url to make the cache file
function getUrl() {
    if (!isset($_SERVER['REQUEST_URI'])) {
    $url = $_SERVER['REQUEST_URI'];
    } else {
    $url = $_SERVER['SCRIPT_NAME'];
    $url .= (!empty($_SERVER['QUERY_STRING']))? '?' . $_SERVER[ 'QUERY_STRING' ] : '';

    }
    return $url;
}                     
Cache($content) function write your page content to destination cache folder 
function cache($buffer) { //page's content is $buffer
    $url = getUrl();

    $filename = md5($url) . '.cache';
    $data = time() . '¦' . $buffer;
    $filew = fopen("cache/" . $filename, 'w');
    fwrite($filew, $data);
    fclose($filew);
    return $buffer;
}
display() function is get the contents from cache location and execute the cache() your cache time
function display() {

    $url = getUrl();
    $filename = md5($url) . '.cache';

    if (!file_exists("cache/" . $filename)) {
    return false;
    }
    $filer = fopen("cache/" . $filename, 'r');
    $data = fread($filer, filesize("cache/" . $filename));
    fclose($filer);
    $content = explode('¦', $data, 2);
    if (count($content)!= 2 OR !is_numeric($content['0'])) {
        return false;
    }
 echo time()-(100).'===='.$content['0'];
    if (time()-(100) > $content['0']) { // 100 is the cache time here!!!
        cache('<strong>bikash ranjan nayak entry into cache html contents file</strong>');
        return false;
    }
        echo $content['1'];
        die();
}

// Display cache (if any)
display();  // if it is displayed, die function will end the program here.

// if no cache, callback cache
ob_start ('cache');
Hope it`s may help you :)



No comments:

Post a Comment