【问题标题】:php cache expiration time for file_exists() or similiar functionsfile_exists() 或类似函数的 php 缓存过期时间
【发布时间】:2016-08-25 21:32:40
【问题描述】:

根据file_exists()的php文档

这个函数的结果被缓存。请参阅 clearstatcache() 了解 更多细节。

但它没有提供关于 php 将在缓存中保存该信息多长时间的信息。我检查了clearstatcache() 的文档 但没有这样的信息。这次谷歌搜索也没有帮助。

我正在构建一个应用程序,其中调用 file_exists 以生成一些输出,并且由于任何用户可以随时删除正在检查的文件,因此我需要在生成输出之前确定它是否真的存在。

在 file_exists() 之前调用 clearcache() 可以解决问题,但出于好奇,我想知道 PHP 将缓存文件信息多长时间(默认时间)以及我可以通过哪个变量来更改缓存过期时间?

编辑1:实际上,删除文件后再次使用file_exists()检查返回false,但如果是这样,文档中写的cache是​​什么意思?

编辑 2:

<? 
var_dump(file_exists('/home/user/filecheck.php')); 
sleep(20);
// after running script, sleep for 20 seconds just to quickly delete this file manually before file_exists is called again.
// unlink is not used since as per documentation it'll clear php cache.
var_dump(file_exists('/home/user/filecheck.php')); 
?>

脚本的响应是

boolean true

boolean false

这意味着即使文件存在,即使相同的执行,php也不会缓存file_exists信息,那么为什么在文档中写“这个函数的结果被缓存”?

【问题讨论】:

  • PHP 在请求期间缓存该信息
  • 请求持续时间???
  • 查看this bug report - You guys realize that the stat cache is per-request, right? You only need to clear the stat cache before a file_exists() call if you A. did a stat for it, and B. either created or deleted it on that request. In which case you shouldn't need to stat it again since the success status of the create/delete will tell you whether the file is there or not. Perhaps for long-running daemons or something this becomes more of an issue, but for a typical web request the stat cache typically saves you dozens of system calls.中的评论
  • @MarkBaker 您指的是日期为 2004-06-15 15:43 的错误现在想起来并不奇怪。我认为这个问题在 11 年内得到了解决……
  • @num8er - 我特别指出了错误中的评论,该评论专门回答了 OP 关于缓存持续时间的问题;虽然我没有看到任何说明该错误已被关闭,但我希望它现在已经解决

标签: php


【解决方案1】:

stat 缓存将信息缓存多长时间可在您的 php.ini 文件中使用 realpath_cache_ttl 变量进行配置。默认似乎是 120 秒。

【讨论】:

    【解决方案2】:

    你不需要clearstatcache(),因为manual说:

    您还应该注意,PHP 不会缓存关于 不存在的文件。所以,如果你在一个文件上调用 file_exists() 不存在,它将返回 FALSE,直到您创建文件。如果你 创建文件,即使您随后删除文件,它也会返回 TRUE。 但是 unlink() 会自动清除缓存。

    同样为了避免一些错误,如果您想检查文件是否存在,最好使用is_file(),而对于目录,最好使用is_dir(),因为如果同时存在的路径是文件或目录,file_exists() 将返回 true。

    附言证明如果文件被删除,它不会被缓存:http://joxi.ru/eAO55BF4ojZjmo

    关于缓存的含义:再次阅读本手册:http://php.net/manual/en/function.clearstatcache.php

    当您使用 stat()、lstat() 或在 受影响的函数列表(如下),PHP 缓存那些信息 函数返回以提供更快的性能。

    这意味着缓存是用于文件统计的,为了不每次都重新读取它,clearstatcache() 删除该文件的统计缓存并强制重新读取它们。

    附:实际上,缓存统计数据而不由用户明确启用它是愚蠢的:ini_set('cache_file_stats', true) 最好将其控制权交给用户。

    【讨论】:

    • 但是如果之前的文件存在并且调用了file_exists,php会缓存文件信息。然后如果文件将被删除,file_exists 将再次返回 true。
    • 你在现实生活中检查过吗?
    • 实际删除文件后再次检查返回false,如果是,那么cache是​​什么意思?
    • 缓存的意思是不重读文件的stats,看:php.net/manual/ru/function.stat.php
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多