PHP cache of some parts of the page

I have sections on a page that require enough resources that I would like to cache, here is an example page.

[=== Some Static HTML ===]
[=== PHP  1 ===]
[=== Some Static HTML ===]
[=== PHP  2 ===]

I would like to put "PHP Script 1" in a cache file, such as script1.html, and include it, rather than processing entire scripts and the same for Script 2.

I have a problem: I can easily cache the entire page and work, but I would just like to cache certain parts (as indicated above), because some things, such as user session data, must be in real time.

I have this class that is designed to stop and start the buffer so that I can pull out certain parts without disturbing the rest of the page, however it does not do what I want. http://pastebin.com/Ua6DDExw

I would like to be able to go as shown below, while it will store the section in a file with simple php inlcude, rather than hitting the database.

HTML Content

<?php
$cache->start_buffer("cache_name");
// PHP 
$cache->end_buffer("cache_name");
?>

HTML Content

<?php
$cache->start_buffer("cache_name");
// PHP 
$cache->end_buffer("cache_name");
?>

I do not have access to memcache or the like, because this will happen on shared hosting.

Any help would be great, Thanks

+5
source share
1 answer

learn the use of ob_start()and ob_flush(). He does what you seek. You will need to manually write it to a file. There are also cache.php classes in the wild.

http://php.net/manual/en/function.ob-start.php

<?php  

  $cache_time = 3600; // Time in seconds to keep a page cached  
  $cache_folder = '/cache'; // Folder to store cached files (no trailing slash)  

  // Think outside the box the original said to use the URI instead use something else.
  $cache_filename = $cache_folder.md5(",MyUniqueStringForMyCode"); // Location to lookup or store cached file  

  //Check to see if this file has already been cached  
  // If it has get and store the file creation time  
  $cache_created  = (file_exists($cache_file_name)) ? filemtime($this->filename) : 0;

  if ((time() - $cache_created) < $cache_time) {  
    $storedData = readCacheFile($cache_filename);
  }
  else
  {

    // Alternatively you can ignore the ob_start/get_contents/end_flush code 
    // and just call a function and store it directly to the variable.
    // Start saving stuff
    ob_start();  

    /** do your work here echoing data to the screen */

    $storedData = ob_get_contents();
    ob_end_flush();

    // create the cachefile for the data.
    createCacheFile($cache_filename);
  }


  // Do stuff with $storedData.
+4
source

All Articles