Dewan159
Dewan159

Reputation: 3074

browser caching or disk caching?

Only days ago I started using browser caching, to cache js and css files and keep it " Not Modified ", and it works very good.

Now I want to apply the same way on many pages of the system. For example, I have this page that lists the "users" from the database, and i want to cache the page not to over-load the database with queries.

My question is: is that even a good method (does the page still execute the db query when cached ?) or should I turn to disk caching or memcached ?

header("HTTP/1.1 304 Not Modified");
header("Expires: ".gmdate("D, d M Y H:i:s", time()+(60*86400))." GMT");
header("Cache-Control: must-revalidate");
mysql_query(" SELECT * FROM `users` ");
// list all users 

Upvotes: 0

Views: 243

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

A simple disk caching example, ive used this method when caching dynamic contant that dosent change often like stats, menus, rssfeeds, pages ect..

<?php 
$cacheTime=3600; /*1hour*/

if(file_exists('./cache/'.sha1('users').'.php') && $_SESSION['user_status']!=true){
    $FileCreationTime = filectime('./cache/'.sha1('users').'.php');
    /* Calculate file age in seconds*/
    $FileAge = time() - $FileCreationTime;
    /*1h cache*/
    if ($FileAge > ($cacheTime)){unlink('./cache/'.sha1('users').'.php');header('Location: '.$_SERVER['REQUEST_URI']);die();}
    include("./cache/".sha1('users').".php");
    /*Cache is there and not older then 1hour so echo the cache*/
    echo base64_decode($cache);
}else{
    /*************************************************************/
    //Cache is NOT there or user logged in or older then 1hour so regenerate content

    //Do Content and store in $return variable
    $return='';


    $result = mysql_query(" SELECT * FROM `users` ");
    while($row=mysql_fetch_assoc($result)){
        $return .='<ul>'.$row['user'].'</ul>';
        ...
    }
    ...
    ...
    $return .='bla bla';
    /*************************************************************/

    /*Check if not logged in else save*/
    if($_SESSION['user_status']!=true){
        $cache_file_encoded = base64_encode($return);
        $cache_file = <<<CACHE
<?php 
/**
* Cached for:Users Page [{$_SERVER["HTTP_HOST"]}{$_SERVER['REQUEST_URI']}] Base64
*/  
 \$cache ="$cache_file_encoded"; ?>
CACHE;
        file_put_contents('./cache/'.sha1('users').'.php',$cache_file);
}
echo $return;
}
?>

Upvotes: 2

Related Questions