Build Cache to Speed Up Website in PHP


Caching the pages will improve the overall site speed. For example, if you have lots of pages that do not update frequently, you can cache these pages into static html. However, the static htmls cached do not change ever after (if you print something e.g. date from the server-side, which changes everytime, it does not reflect on the cached pages).

My webhosting company shuts my FTP down quite a few times before because my PHP scripts were using a high resource that may affect other shared-hosts on the same machine. I have been optimising the PHP code since then. Due to a high demand from the users or search engines (e.g. mainly googlebots), sometimes, the CPU usages strike high as before. I had to limit the concurrent threads from the search engines and redirect some of them to a static page indicating server busy.

Here is the quick idea and implementation that will reduce the server CPU usage for PHP pages. In my case (e.g. steakovercooked.com), the PHP interpretes the QUERY_STRING and redirects to different pages. The first time, the PHP will check if the cache is available, if yes, simply read this file and flush to the browser. Otherwise, the PHP script for that page will be executed but using ob_start(), ob_get_contents() at the end to write the contents (as html, of course) to cache page, which will be in use next time e.g. press F5 to refresh. Using ob_start(“gz_handler”) works like a magic that will compress the page content. This will shorten a lot the downloading time. Usually, this is put at the beginning of PHP script before any outputs are made.

The following snippet of PHP code illustrates this idea. Simple but powerful. If you check my website, you will notice the difference.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
    if ($_SERVER['REQUEST_METHOD'] == 'GET') 
    {
      $cachepage = 'cache/'.$_lang.'/'.$_SERVER["QUERY_STRING"].'.html'; // path of cache page to check
      if (file_exists($cachepage))
      {
        $nonpages=array("System.Online"); // these pages do not load caches
        if (in_array($pageurl, $nonpages))
        {
          include("body.php");
        }
        else
        {
          ob_start('ob_gzhandler'); // compressing the output
          $sz = round(filesize($cachepage)/1024, 2);
          echo '<font style="position:absolute;left:0;top:0" size="3px" color="yellow">Fetched from Cache: '.$sz.' KB</font>';
          if ($_lang==2) // traditional Chinese
          {
            include('big5.php');
            if (!is_null($ZLAI_CHINESE))
            {
              ob_start('ZLAI_CHINESE_getchar');
            }
          }        
          readfile($cachepage); // load the cache
        }
        die();
      }
      else
      {
        // not cached yet
        include("body.php");
        if (!$_isSE)
        {
          // disable search engine save cache
          $output = ob_get_contents();  
          file_put_contents($cachepage, $output); // write to the cache file
        }
      }
    }
    else
    {
      // not cache for POST pages
      include("body.php");
    }
?>
<?php
    if ($_SERVER['REQUEST_METHOD'] == 'GET') 
    {
      $cachepage = 'cache/'.$_lang.'/'.$_SERVER["QUERY_STRING"].'.html'; // path of cache page to check
      if (file_exists($cachepage))
      {
        $nonpages=array("System.Online"); // these pages do not load caches
        if (in_array($pageurl, $nonpages))
        {
          include("body.php");
        }
        else
        {
          ob_start('ob_gzhandler'); // compressing the output
          $sz = round(filesize($cachepage)/1024, 2);
          echo '<font style="position:absolute;left:0;top:0" size="3px" color="yellow">Fetched from Cache: '.$sz.' KB</font>';
          if ($_lang==2) // traditional Chinese
          {
            include('big5.php');
            if (!is_null($ZLAI_CHINESE))
            {
              ob_start('ZLAI_CHINESE_getchar');
            }
          }        
          readfile($cachepage); // load the cache
        }
        die();
      }
      else
      {
        // not cached yet
        include("body.php");
        if (!$_isSE)
        {
          // disable search engine save cache
          $output = ob_get_contents();  
          file_put_contents($cachepage, $output); // write to the cache file
        }
      }
    }
    else
    {
      // not cache for POST pages
      include("body.php");
    }
?>

In [here], it describes a few improvements that can be made to polish this PHP caching framework.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
525 words
Last Post: Hello World Program in LOGO
Next Post: Index Sorting in PHP

The Permanent URL is: Build Cache to Speed Up Website in PHP

Leave a Reply