create php cache with file_get_contents

1.8k views Asked by At

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);
}
?>
2

There are 2 answers

0
deanpodgornik On BEST ANSWER

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);
1
ceejayoz On

file_get_contents() gets the contents of a file, it doesn't execute it in any way. include() will execute the PHP, but you have to use an output buffer to grab its output.

ob_start();
include('includes/menu.php');
$cache = ob_get_flush();
file_put_contents($cache_file, $cache);