Papermashup

Subscribe


Tweets


"@burgerbeartom @kycutwilson finally got around to using my free burgers for life! And we weren't disappointed. http://t.co/nJ6p2nLtg4"

@ashleyford 7 days ago

"RT @MAA: Insight from @CommunicatorHQ on the need for brands to take a long view on social responsibility http://t.co/4wWA3A2TOc"

@ashleyford 2 weeks ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Caching Dynamic PHP pages easily

AshleyAshley

I’ve been looking for a solution to cache heavy pages and just serve a static html version for a little while now, and I’ve found a solution in output buffering.

Things to think about

It’s not a good idea to go away and cache your entire site, you need to think about which pages receive high traffic, and which pages make a number of database requests. Static HTML pages aren’t going to see a benefit from caching and may in fact be served slower due to PHP invoking the request to the cached version. as an example I’m using caching on dotdashcreate.com homepage as there are a number of database requests that could easily be cached, the cached version of the page is stored here.

If you run a big site or blog I would certainly recommend caching your homepage as this will usually be your visitors first point of contact thus generating more traffic. Its probably not a good idea to cache individual posts that allow comments etc, unless you are willing to write a script to re-cache the page.

You need to allow write access to the cache directory, in the code example this is /cache/. There’s quite a bit going on in the script, the first two lines set the path to the cached directory and the time frame to refresh the cache, we then do a check to see if the cached file is older than the cache time, if it is then it refreshes the cached version (which is the block of code at the bottom), if not it just serves the cached version.

The Code:



$cachefile = 'cache.html';
$cachetime = 4 * 60;
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    include($cachefile);
    echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->n";
    exit;
}
ob_start(); // Start the output buffer

/* Heres where you put your page content */

// Cache the contents to a file
$cached = fopen($cacheFile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser

demo

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 63
  • Ken Le
    Posted on

    Ken Le Ken Le

    Reply Author

    Try this one, go to Example, they have an example for caching whole website.
    This class http://www.phpfastcache.com is supported Files, APC, Memcached and more.. It’s simple for newbie


  • Grand theft auto 5 pc download
    Posted on

    Grand theft auto 5 pc download Grand theft auto 5 pc download

    Reply Author

    Thank you, however im having difficulties caching same page with 3 different changing variables. anyway thanks for help


  • is green tea good for weight loss
    Posted on

    is green tea good for weight loss is green tea good for weight loss

    Reply Author

    I’m excited to discover this web site. I want to to thank you for ones time due to this fantastic read!! I definitely savored every bit of it and I have you saved as a favorite to see new things in your website.


  • automotive battery charger
    Posted on

    automotive battery charger automotive battery charger

    Reply Author

    You made several good tips there. I did a search on the subject and discovered
    a lot of people will agree with your blog. Wonderful Job,
    Chow!


  • Michael Kors Handbags Outlet
    Posted on

    Michael Kors Handbags Outlet Michael Kors Handbags Outlet

    Reply Author

    I have read so many articles or reviews concerning the blogger lovers except this article is in fact a
    good paragraph, keep it up.


  • Fatriff
    Posted on

    Fatriff Fatriff

    Reply Author

    Recently I started a new project where the best solution would be to generate static pages using this method because everything on the site is dynamic so having constantly changing text and things would hurt the site in seo.. So i’m glad I found this again!


  • jackie
    Posted on

    jackie jackie

    Reply Author

    I love you so


  • non prescription glasses
    Posted on

    non prescription glasses non prescription glasses

    Reply Author

    Very great post. I just stumbled upon your weblog and wanted to mention that I’ve really loved browsing your blog posts. In any case I’ll be subscribing for your feed and I’m hoping you write again very soon!


  • toenail fungus treatment mn
    Posted on

    toenail fungus treatment mn toenail fungus treatment mn

    Reply Author

    , provides effective Jacksonville toenail fungus choose to members
    with the community using technologically advanced methods
    that include laser care. Even after successful treatment, the fungus may return.
    Apart from these natural treatments one must also take certain precautions in keeping chlamydia away.


  • Bob Cavezza
    Posted on

    Bob Cavezza Bob Cavezza

    Reply Author

    FYI the variables are not consistent in the code above. $cacheFile should be named $cachefile on this line:

    Incorrect:
    $cached = fopen($cacheFile, ‘w’);

    Correct: $cached = fopen($cacheFile, ‘w’);
    $cached = fopen($cachefile, ‘w’);

    Cheers!


  • goals mad
    Posted on

    goals mad goals mad

    Reply Author

    excellent post I’m a huge football fan looking forward for the 2012-2013 season


  • Carlos
    Posted on

    Carlos Carlos

    Reply Author

    OK – I just discovered unlink() :)

    thanks again for posting this


  • Carlos
    Posted on

    Carlos Carlos

    Reply Author

    thanks for this very clean solution !!

    I am also wondering if there is a way that an admin could flush the cache from another page for content editing purposes


  • Free computer support
    Posted on

    Free computer support Free computer support

    Reply Author

    Nice article, very well written.


  • Dan
    Posted on

    Dan Dan

    Reply Author

    I have just set this up, and it works well. For those who run expensive sql queries the same approach can be applied for some very big improvements.

    Dan


  • SirTechALot.com
    Posted on

    SirTechALot.com SirTechALot.com

    Reply Author

    Interesting post. I also use the WordPress Caching plugin for my blog. It works great. On other large ecommerce sites, I’ve often rolled my own caching backend. As an admin user changes a product, adds a new category – the caching program would kick in and rerip new static HTML / PHP pages from the dynamic PHP code I had created. One trick to pull this off is to call your dynamic PHP front-end scripts like a real user using file_get_contents. Then, store that data into a new file for customers to hit. It requires a bit of hacking to get the caching program built, but once it’s in place, you can regenerate the cached version of your site with a click.


  • xenang
    Posted on

    xenang xenang

    Reply Author

    oh.It seems very simple! thanks for sharing


  • Onore
    Posted on

    Onore Onore

    Reply Author

    Very simplify and works tutorial, Thanks.


  • Mangalore webdesign
    Posted on

    Mangalore webdesign Mangalore webdesign

    Reply Author

    its work-) great php tutorilas to beginers,,,thank you


  • csr
    Posted on

    csr csr

    Reply Author

    very simple caching….


  • CostSolutions.Org
    Posted on

    CostSolutions.Org CostSolutions.Org

    Reply Author

    Great solution.. Cache-ing is difficult. If users are seeing old content, they are gone.. GJ.


  • Delta
    Posted on

    Delta Delta

    Reply Author

    Hi,
    I have Any Login Form In Index Page ! Now After Login Your Code Re Generate Cache?
    How To Best Chaching Page For Any Index Page With Login Form ?

    Thanks


  • Diego
    Posted on

    Diego Diego

    Reply Author

    Man that’s a very good solution, and simple! Tanks for sharing!


  • DC Web Design
    Posted on

    DC Web Design DC Web Design

    Reply Author

    Hey Sven good work with the guide man.


  • Bundesverdienstkreuz
    Posted on

    Bundesverdienstkreuz Bundesverdienstkreuz

    Reply Author

    It’s a pity you don’t have a donate button! I’d most certainly donate to this outstanding blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this site with my Facebook group. Chat soon!


  • Sven
    Posted on

    Sven Sven

    Reply Author

    I wrote I little guide where I store cache files using php and read them using apache and c++. The performance gain is really great. Read more about it:
    http://sven.webiny.com/advanced-cache-mechanism-using-php-cpp-and-apache/


  • web tasarim sitesi
    Posted on

    web tasarim sitesi web tasarim sitesi

    Reply Author

    useful. thank you for article.


  • daffin
    Posted on

    daffin daffin

    Reply Author

    Thanks…


  • CodesTips
    Posted on

    CodesTips CodesTips

    Reply Author

    Caching is very usefull on website with big databases. I wrote a post about cache on my blog:cache file in php


  • Daniel
    Posted on

    Daniel Daniel

    Reply Author

    Thanks…

    Just installed the code, works really well ! !

    Nice and easy is how I like it…


  • Davinder
    Posted on

    Davinder Davinder

    Reply Author

    Hello.
    I love this tutorial but there is a problem
    Why not use PHP strip slashes e.g. if i type in (with out the spaces) i could easily cross refrence……. your site


  • Tommy M
    Posted on

    Tommy M Tommy M

    Reply Author

    @Marc, @Steve, @ Ashley.

    filectime is more accurate, so I implemented that with Marc’s advice.

    Additionally, Steve is correct to use readfile. It ran considerably faster!

    Thanks for this great technique!


  • Marc
    Posted on

    Marc Marc

    Reply Author

    Idea is good, but filemtime is innacurate to give the last time the file was modified for that case. If you try it you will see.. you can modify the file and unix will tell php that the file was modified on the date it was created. Use filectime to get the last time the inode of the file was changed, since you overwrite the file each X seconds, the inode meta data will change, giving you valid informations about the file.


  • Steve Clay
    Posted on

    Steve Clay Steve Clay

    Reply Author

    You might as well send HTTP cache headers as well: header(‘Cache-Control: public, max-age=’ . $cacheTime);

    Also, you might get a slight perf boost using readfile() over include, since the cache file will have no PHP blocks.


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @steve good point with the cache header, never used readfile() will have to look into that. Thanks for the feedback :)


  • jebaird
    Posted on

    jebaird jebaird

    Reply Author

    First off I have gota say that this caching idea kicks ass.
    I have created a class based on the original code and user comments code. Also i fixed a couple of bugs:

    here is the link:
    http://www.jebaird.com/blog.php?year=2009&month=03&cat=3&id=32


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      Hey Jebaird,

      Great response and thanks for the comment 😉

      Ashley


  • Jurriën Dokter
    Posted on

    Jurriën Dokter Jurriën Dokter

    Reply Author

    Used it, in my “freshly” created cms. Works like a charm!


  • AzeriFire
    Posted on

    AzeriFire AzeriFire

    Reply Author

    Thank you admin :)
    There are some new correction too:
    Replace this one:
    [ecko_code_highlight]if (isset($_SERVER[‘REQUEST_URI’])) // Is there any URI to cache
    [/ecko_code_highlight]

    with this one:

    [ecko_code_highlight]if (isset($_SERVER[‘REQUEST_URI’]) && $_SERVER[‘REQUEST_URI’]!=”/”) [/ecko_code_highlight]

    to escape problems when site URL ends with slash (http://site.com/)

    Latest version is here:
    http://paste.org/5666

    P.S. Sorry for spam


  • AzeriFire
    Posted on

    AzeriFire AzeriFire

    Reply Author

    Hi. Thank you for this little, but powerful code. I use SEF URL on my sites. There are problem with “/” (slash). If site URI ll be for sample – /nokia/n97/comments/page/1.html this cache script will look for cache folder, then nokia folder, then inside of nokia folder for n97 subfolder and etc… There are will be PHP errors on site (Not found page and etc.). I improved it little more.And use global variable to define is the caching this page indeed. For sample, I don’t need caching login page and etc. I use $useCache variable ($useCache=0 to disable, =1 to enable caching currently viewing page.)
    And finally improved script:
    http://paste.org/5665
    OR
    http://www.pastethat.com/use_cache_with_p

    Thanks again!
    P.S. Sorry for my poor English.


    • admin
      Posted on

      admin admin

      Reply Author

      AzeriFire,

      Thanks for the comments and code update! Glad to hear you found it useful and adapted the code in your own way.

      Ashley


  • Andrew Gill
    Posted on

    Andrew Gill Andrew Gill

    Reply Author

    Great article. My homepage (index.php) is also calling the database many times. So i’ve used your approach slightly differently by creating an index.html page in the root so there is no need for the include.


  • Traducciones
    Posted on

    Traducciones Traducciones

    Reply Author

    nice post! i will use it


  • Patternhead
    Posted on

    Patternhead Patternhead

    Reply Author

    If you’re using using WordPress then the wp-supercache plugin works pretty well!


  • Ashley
    Posted on

    Ashley Ashley

    Reply Author

    That’s a great point, I should have mentioned that in my post! I’m currently using the wp-supercache plugin, well worth installing if you anticipate spikes in blog traffic.