Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Cache specific parts of a page

Tags:

php

caching

I have sections on a page that require a fair amount of resources that I would like to cache, here is an example of the page.

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

I would like to put "PHP Script 1" into a cache file eg script1.html and include it rather than processing the whole script, and the same for Script 2.

The problem I have is I can cache the whole page easily and it works but I would like to just cache specific parts (as above) because some things like user session data needs to be live.

I have this class that is meant to be able to stop and start the buffer so I can pull out specific parts without breaking the rest of the page however it doesn't do what I want. http://pastebin.com/Ua6DDExw

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

HTML Content

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

HTML Content

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

I don't have access to memcache or anything else like that because this will be going on shared hosting.

Any help would be great, Thanks

like image 416
Story Teller Avatar asked Oct 09 '22 18:10

Story Teller


1 Answers

look into using ob_start() and ob_flush() It does what you are looking to do. You'll need to manually write it to a file. There are cache.php classes out in the wild as well.

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.
like image 186
thenetimp Avatar answered Oct 12 '22 11:10

thenetimp