Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

page caching using php

Tags:

php

caching

i am seeking for guidance from all of u who can tell me about page caching for a website... i am working in php so if anyone can explain me how to perform caching in php.

like image 566
akku Avatar asked Mar 02 '10 06:03

akku


2 Answers

PHP offers an extremely simple solution to dynamic caching in the form of output buffering. The front page of the site (which generates by far the most traffic) is now served from a cached copy if it has been cached within the last 5 minutes.

<?php

  $cachefile = "cache/".$reqfilename.".html";
  $cachetime = 5 * 60; // 5 minutes

  // Serve from the cache if it is younger than $cachetime
  if (file_exists($cachefile) && (time() - $cachetime
     < filemtime($cachefile))) 
  {
     include($cachefile);
     echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." 
     -->n";
     exit;
  }
  ob_start(); // start the output buffer
?>

.. Your usual PHP script and HTML here ...

<?php
   // open the cache file for writing
   $fp = fopen($cachefile, 'w'); 

   // save the contents of output buffer to the file
    fwrite($fp, ob_get_contents());

    // close the file

    fclose($fp); 

    // Send the output to the browser
    ob_end_flush(); 
?>

This is a simple cache type,

you can see it here

http://www.theukwebdesigncompany.com/articles/php-caching.php

You can use Smarty has cache technique

http://www.nusphere.com/php/templates_smarty_caching.htm

like image 116
sathish Avatar answered Sep 30 '22 14:09

sathish


I'm rather surprised that none of the responses so far seem to have addressed the possibility of caching anywhere OTHER than on the server where PHP is running.

There's a lot of functionality within HTTP to allow proxies and browsers to re-use content previously supplied without having to refer back to the origin. So much so that I wouldn't even try to answer this in a S.O. reply.

See this tutorial for a good introduction to the topic.

C.

like image 21
symcbean Avatar answered Sep 30 '22 14:09

symcbean