PHP full page cache

17.Aug.2010

Whenever you are building dynamic (PHP) website it is a good option to consider caching. Why should you consider PHP caching?

  1. You won’t be running a whole PHP script on your server.
  2. You won’t send queries to database.
  3. You don’t have to have connection to a database.
  4. You will have less load on server.
  5. You will have better performance.

In order to make the simpliest PHP caching possible, just copy/paste following two snippets.

Include this snippet into header:

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
$requestUri = $_SERVER['REQUEST_URI'];
if (empty($requestUri)) {
    $requestUri = 'index.php';
}
 
$seconds = (1 * 60 * 60);
$cachedFile = md5($requestUri);
$filename = $_SERVER['DOCUMENT_ROOT'] .  '/cache/' . $cachedFile . '.php';
 
$cache = true;
 
//pages / URIs you don't want to have in cache
//usually pages that receive POST or GET parameters
$nonCacheablePages = array(
    '/some-post-page/post',
    '/search.php',
);
 
foreach ($nonCacheablePages as $nonCacheablePage) {
    if (substr($requestUri, 0, strlen($nonCacheablePage)) === $nonCacheablePage) {
        $cache = false;
        break;
    }
}
 
if ($cache && file_exists($filename) && (filemtime($filename) + $seconds > time())) {
    include $filename;
    die;
}
 
if ($cache) {
    ob_start();
}

Include following snippet in footer:

1
2
3
4
5
if ($cache) {
    $output = ob_get_contents();
    file_put_contents($filename, $output);
    ob_flush();
}

You could improve this basic PHP caching by checking if database connection is available, and if it is not available, you could force caching so users would still be presented with page. Other improvements could base on saving location of cache file so you don’t get one folder filled with cached pages. This would improve performance even more.