file_put_contents 创建新文件

file_put_contents create new file

当缓存文件已经存在时,我的下面的脚本可以工作,但不会创建初始的第一个缓存文件本身。

有人可以帮我吗?
文件夹权限没问题。

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

}

?>

您只在文件存在且旧的情况下写入该文件。您应该更改 if,以便它在不存在时写入它。

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

?>

你的条件是告诉 PHP 到 "include the file if the file does not exist"。

这就是脚本从一开始就不会创建缓存文件的原因,因为在每次脚本加载(包括第一个)时,您的条件状态 "If there is no file, include the file"。

您需要制作条件 "file not exist",例如:

if(!file_exists($cache_file)) {

  // File does not exist - create the file

} else {  

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

}