Skip to content
Advertisement

How do I cache a web page in PHP?

how do I cache a web page in php so that if a page has not been updated viewers should get a cached copy?

Thanks for your help. PS: I am beginner in php.

Advertisement

Answer

You can actually save the output of the page before you end the script, then load the cache at the start of the script.

example code:

<?php

$cachefile = 'cache/'.basename($_SERVER['PHP_SELF']).'.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds

if (file_exists($cachefile) && time() - $cachetime <= filemtime($cachefile)) {
  $c = @file_get_contents($cachefile);
  echo $c;
  exit;
} else {
  unlink($cachefile);
}

ob_start();

// all the coding goes here

$c = ob_get_contents();
file_put_contents($cachefile, $c);

?>

If you have a lot of pages needing this caching you can do this:

in cachestart.php:

<?php
$cachefile = 'cache/' . basename($_SERVER['PHP_SELF']) . '.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds

if (file_exists($cachefile) && time() - $cachetime <= filemtime($cachefile)) {
  $c = @file_get_contents($cachefile);
  echo $c;
  exit;
} else {
  unlink($cachefile);
}

ob_start();
?>

in cacheend.php:

<?php

$c = ob_get_contents();
file_put_contents($cachefile, $c);

?>

Then just simply add

include('cachestart.php');

at the start of your scripts. and add

include('cacheend.php');

at the end of your scripts. Remember to have a folder named cache and allow PHP to access it.

Also do remember that if you’re doing a full page cache, your page should not have SESSION specific display (e.g. display members’ bar or what) because they will be cached as well. Look at a framework for specific-caching (variable or part of the page).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement