file_put_contents create new file

1k views Asked by At

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';

}

?>
2

There are 2 answers

1
Barmar On BEST ANSWER

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';
}

?>
0
James On

Your conditional is telling PHP to "include the file if the file does not exist".

Which is why the script never creates the cache file in the first place, because on every script load (including the first one) your conditional states "If there is no file, include the file".

You need to make the conditional "file not exist", like:

if(!file_exists($cache_file)) {

  // File does not exist - create the file

} else {  

  // File does exist - show the file (include)

}