Pear Cache Lite Implementation for PHP Websites

by Hiroshi on February 3, 2013

in cache

We have earlier given a cache script to cache PHP websites. Here is another ready to use open source solution. This package is a little cache system optimized for file containers. It is fast and safe (because it uses file locking and/or anti-corruption tests). Implementation is really easy.

Edit Lite.php file and define cache directory, cache lifetime, enable/disable cache, file locking, and more:

I am using here folder named as “siteCache” to store cache files, that is located at website root.

var $_cacheDir = 'siteCache/';

Cache script files are in ‘cache_lite‘.

cache_lite > Cache > Lite.php

Copy cache_lite in the root and edit Lite.php

Then here is how you implement this cache in pages. siteCache in script here is cache folder thats located in root of site.

Include this code in every page (at top) or call in at top of every page.

$options = array(
    'cacheDir' => 'siteCache/',
    'lifeTime' => 1000
$cache = new Cache_Lite_Output($options);
if (!($cache->start($_SERVER['REQUEST_URI']))) {

OR like this

// at top of every page
$options = array(
    'cacheDir' => 'siteCache/',
    'lifeTime' => 1000
$cache = new Cache_Lite_Output($options);
if (($cache->start($_SERVER['REQUEST_URI']))) {
all site page content goes here or include a php page to cache
// in footer of every page
<?php $cache->end(); ?>


/* Include the class */
require_once 'cache_lite/Output.php';
/* Set a key for this cache item */
$id = 'newsitem1';
/* Set a few options */
$options = array(
    'cacheDir' => '/var/www/',
    'lifeTime' => 3600
/* Create a Cache_Lite object */
$Cache_Lite = new Cache_Lite($options);
/* Test if there is a valid cache-entry for this key */
if ($data = $Cache_Lite->get($id)) {
    /* Cache hit! We've got the cached content stored in $data! */
} else {
    /* Cache miss! Use ob_start to catch all the output that comes next*/
    /* The original content, which is now saved in the output buffer */
    include "content-page-to-cache.php";
    /* We've got fresh content stored in $data! */
    $data = ob_get_contents();
    /* Let's store our fresh content, so next
     * time we won't have to generate it! */
    $Cache_Lite->save($data, $id);
echo $data;

For above code, here is how you purge cache for page that has been updated:

if (isset($_POST["add_comment"]) && $_POST["add_comment"]){

Download unofficial example of script that I am using from below:

Cache_lite Implementation Example


This cache will also cache everything, part of page or full page depending on implementation method. Forms, sessions, login forms, get/post variables will not behave properly unless you put this cache right.


Delete cache, if form is being submitted or sessions are being stored, or at user login and logout.

Go to link below for official and original Cache Lite page.

Download Pear Cache

Download Pear Cache – Official

Related Posts

Previous post:

Next post: