0

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);
}
?>
  • You need to capture and store the `buffer` output of the `php` file and not the `php` file itself. Please take a look at https://secure.php.net/manual/en/function.ob-start.php – Kevin Jung Jun 26 '15 at 19:29

2 Answers2

2

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);
deanpodgornik
  • 322
  • 2
  • 7
1

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);
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
  • `ob_get_clean` may also be useful to you. `flush` will output it as well as caching it, while `clean` will not output it - you'd have to echo it yourself as desired. – ceejayoz Jun 26 '15 at 19:34