How caching saves your server from Digg !
No matter where you are hosting your site, you should optimize your site for improved performance of the server. If like me you are on a cheap shared hosting, it makes more sense to optimize .. otherwise if your site gets a lot of traffic your server and the other sites on your server will get thrashed. I use wordpress for this blog and when today I realized one of my articles has made it to the first page of digg.com .. ( Cheapest broadband, DSL and Cable internet. Comcast SBC DSL ) .. I immediately installed the plugin wp-cache !! And the load on my server is down to a fraction now !!
The idea is to reduce the load of the php and perl files (or any other dynamic scripts on your site) and serve html pages … or have the php file just open a cache file and serve the file. If you have a popular software, just search for a caching plugin / module / addon and install it. If you are using your own scripts .. like I do .. its not so complicated to provide caching. This is what you need to do. Please use the notes below as pointers and do your research. I am no expert .. you can use this code as a guideline ..
For a perl file .. .. have something like this .. parse the input params .. for eg .. if its search.pl .. and people are searching for “some word” .. then your cache file name could be some_word.txt
if (-e $cache_file) {
open(CF, “$cache_file”);
@lines =
close CF;
print @lines;
exit(1);
} else {
$CACHE_IT = 1;
open(CF, “>$cache_file”);
…..
and print the output into the cache file. With php its much simpler … just add these lines to the beginning of the script ..
$cache_max_time = 60 * 60 * 3; // SECS
$mtime = @filemtime($cache_file);
if ($mtime + $cache_max_time > time() ) {
$content = file_get_contents($cache_file);
echo $content;
} else {
// will be discussed ..
}
in php its very simple to get the contents of the output buffer … add ob_start(”my_func”) and this function will be called finally with the output buffer.. so the code to overwrite the cache file will be :
function my_func($content) {
$fh = fopen($cache_file, ‘w’) or die(”can’t open file”);
fwrite($fh, $content);
fclose($fh);
return $content;
}
So use this as guideline and write your own caching code. We webmasters spend a lot of time writing content , scripts and marketing our sites… but we do not pay much attention to the server load .. till one day we get kicked out from our webhosts. Trust me .. its wise to spend some time and weed out inefficient code .. if your site is tuned right .. great .. if not.. its time now !!
[pls link to us if you liked the article]