Search code examples
phpcachingfile-put-contents

file_put_contents create new file


My below script works when the cache file is already present, but does not create the initial first cache file itself.

Can somebody help me?
The folder permissions are fine.

<?php 
$cache_file = 'cachemenu/content.cache';

if(file_exists($cache_file)) {
  if(time() - filemtime($cache_file) > 86400) {

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

  } 

  else include 'cachemenu/content.cache';

}

?>

Solution

  • You're only writing to the file if it exists and it's old. You should change the if so it writes to it if it doesn't exist as well.

    <?php 
    $cache_file = 'cachemenu/content.cache';
    
    if(!file_exists($cache_file) || time() - filemtime($cache_file) > 86400) {
    
        ob_start();
        include 'includes/menu.php';
        $buffer = ob_get_flush();
        file_put_contents($cache_file, $buffer); 
    } else {
        include 'cachemenu/content.cache';
    }
    
    ?>