How do I cache a web page in PHP?
Asked Answered
X

6

17

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.

Xuanxunit answered 10/10, 2009 at 8:22 Comment(3)
Are you using any framework such as Zend Framework? Give us more details!Extractive
I am not using any framework.Xuanxunit
you might want to consider moving it to a framework. code.google.com/p/samstyle-php-framework - full fledged framework that includes file caching and supports memcacheKilogram
K
21

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).

Kilogram answered 10/10, 2009 at 8:32 Comment(8)
noticed the part where i wrote // all the coding goes here? you can put your main code there.Kilogram
check the updated post. you can put the code into seperated php files and include them. remember - Don't Repeat Yourself (DRY) policy.Kilogram
@Kilogram how about not making redundant includes and use functions.Gurney
@Vallentin this is a just simple explanation suitable for those who wish to learn the basic mechanism. How about not using functions and get caching libraries via Composer?Kilogram
@Kilogram if you wanted to keep it simple, then you wouldn't have mentioned the DRY principle. Also, creating two small functions yourself is way more lightweight then having to include a process more dependencies.Gurney
@Vallentin, you have 3k rep. You are free to edit this answer.Kilogram
@Kilogram : an answer below suggests it should be file_put_contents($cachefile,$c) (with the extra $c parameter). Can you confirm/deny?Cheadle
@Cheadle it's been 13 years, I haven't coded in PHP since at least 10 years ago. I doubt I'll recommend my answer as the method to cache output, but it's a basic PHP idea that's possible. thanks for catching this.Kilogram
G
4

Additionally to mauris answer I'd like to point this out:

You have to be careful when you use caching. When you have dynamic data (which should be the case when you use php instead of static html) then you have to invalidate the cache when the corresponding data changes.

This can be pretty easy or extremely tricky, depending on your kind of dynamic data.

Update

How you invalidate the cache depends on the concrete kind of caching. You have to know which cache files belong to which page (and maybe with user input). When the data changes you should delete the cached file or remove the page output from your cache data structure.

I can't give you any more detailed info about that without knowing which implementation you use for caching.

Other folks suggested for example the Pear package or memcached. These have the necessary functions to invalidate the whole cache or parts of it when data changes.

Gilgamesh answered 10/10, 2009 at 8:35 Comment(2)
@Patrick, Actually, caching requires access to the hard disk. Wouldn't it be slower then?Archimage
Well, usually the OS has it's own file cache, so even if you use files, it may be served from memory. but even is not, it is most of the time more performant to read the cached result from disk and return it than recalculating the page. If it's faster to calculate it, then don't cache.Gilgamesh
J
3
$c = ob_get_contents();
file_put_contents($cachefile);

correct is

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

otherwise the script will not work.

Jaal answered 27/1, 2014 at 20:53 Comment(0)
E
0

Use memcached. There's an explanation of how to do it on that site.

Ehrman answered 10/10, 2009 at 8:27 Comment(0)
H
0

Use Squid or update the HTTP headers correctly to do browser caching. I don't see the need to spin your own version of caching based on the question.

Hermie answered 10/10, 2009 at 8:33 Comment(0)
W
0

PEAR has a caching package (actually two):

http://pear.php.net/package/Cache and
http://pear.php.net/package/Cache_Lite for smaller apps

I once used the Cache package (first one) for query caching and at that time it did its work as far as I remember.

Whipstitch answered 10/10, 2009 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.