Search code examples
phpfile-get-contentsfile-put-contents

create php cache with file_get_contents


I am trying to create a cache file from a menu that takes random data called 'includes/menu.php' the random data is created when I run that file manually, it works. Now I want to cache this data into a file for a certain amount of time and then recache it. I am running into 2 problems, from my code cache is created, but it caches the full php page, it does not cache the result, only the code without executing it. What am I doing wrong ? Here is what I have until now :

<?php
$cache_file = 'cachemenu/content.cache';
if(file_exists($cache_file)) {
  if(time() - filemtime($cache_file) > 86400) {
     // too old , re-fetch
     $cache = file_get_contents('includes/menu.php');
     file_put_contents($cache_file, $cache);
  } else {
     // cache is still fresh
  }
} else {
  // no cache, create one
  $cache = file_get_contents('includes/menu.php');
  file_put_contents($cache_file, $cache);
}
?>

Solution

  • This line

    file_get_contents('includes/menu.php');
    

    will just read the php file, without executing it. Use this code instead (which will execute the php file and save the result into a variable):

    ob_start();
    include 'includes/menu.php';
    $buffer = ob_get_clean();
    

    And then, just save the retrieved content ($buffer) into file

    file_put_contents($cache_file, $buffer);