When your site is under a heavy server load you will soon understand why it is important to cache your scripts. Caching will take a load off your server by serving up static content that doesn’t have to put the PHP processor under an intense strain. Your best bet for setting the speed at which this script caches your data is by putting it on a cron task.
So how might you do this? Well here I will show you a basic snippet that has worked well for me.
Note the ### DYNAMIC BEGIN –> ############################# part. It’s where you need to put any tracking scripts or what-not into.
Snippet (MUST GO AT VERY TOP OF YOUR SCRIPT):
-
<?php
-
// Simple PHP Page Caching Snippet
-
// best to use cron and put this in a timer
-
// eg) /usr/bin/lynx –dump http://yoursite.com/scriptname.php?&cacheit=cache > /dev/null
-
// http://thedevnet.com/php/snippets/simple-php-caching-snippet/
-
-
-
// put your ini_set, ob_start, session_start after this line
-
ini_set('zlib.output_compression_level', 1);
-
ob_start('ob_gzhandler');
-
-
-
/* BEGIN –> Cache ->> above all else */
-
$cachedir = "./bobo_cache/";
-
$scriptname = $_SERVER['SCRIPT_NAME'];
-
-
-
function make_cache()
-
{
-
global $cachedir;
-
global $scriptname;
-
-
$scripturl = $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
-
$data = file_get_contents($scripturl."?&system=yes");
-
-
// geez for compatibility purposes i do make sacrifices 8 (
-
$fp = fopen($cachedir.$scriptname,"w+");
-
flock($fp, LOCK_EX);
-
ftruncate($fp, 0);
-
fwrite($fp, $data);
-
fclose($fp);
-
}
-
-
-
if(@$_GET['cacheit'] == "cache")
-
{
-
make_cache();
-
die();
-
}
-
-
// uncomment the following line if you do not wish to use cron
-
// if(rand(1,50) == 10) make_cache(); // roll a 50 sided dice; if its a 10 then make cache
-
-
/* END –> Cache ->> above all else */
-
-
-
-
-
-
# <!– BEGIN Caching Mechanism –>
-
// if you have pagination or something that you would like to continue to load dynamically
-
// say ?p=1 or what not might be good to add an exclusion to the if statement
-
// eg) if( @empty($_GET['system']) && @empty($_GET['p']) )
-
if( @empty($_GET['system']) )
-
{
-
### DYNAMIC BEGIN –> #############################
-
// put your dynamic stuff here (tracking scripts, dynamic content, etc)
-
-
### <– DYNAMIC END #############################
-
-
// if the cache exists then use it and kill processing.
-
if(file_exists($cachedir.$scriptname))
-
{
-
include_once($cachedir.$scriptname);
-
die("\r\n\r\n<!– Bobo Cached Version –>");
-
}
-
// if it couldn't find a cache it'll continue loading as a failsafe
-
}
-
# <!– END Caching Mechanism –>
-
-
-
?>
GD Star Rating
loading...
Originally posted 2009-10-22 09:44:55.
Popularity: 7%
Posted by irbobo @ 23 July 2010