【问题标题】:Fetching file permissions multiple times in PHP doesn't seem to work在 PHP 中多次获取文件权限似乎不起作用
【发布时间】:2021-12-23 18:55:02
【问题描述】:

多次调用PHP函数fileperms时,似乎文件权限显示不正确了:

chmod('file.txt', 0600); 
if ((fileperms('file.txt') & 0777) === 0600) {} // this is true

chmod('file.txt', 0660); 
if ((fileperms('file.txt') & 0777) === 0660) {} // this is false

chmod('file.txt', 0666); 
if ((fileperms('file.txt') & 0777) === 0666) {} // this is false

文件的权限已更改,但对 fileperms 的调用显示了不同的值。是否发生了一些缓存?

【问题讨论】:

  • $file.txt vs file.txt ?
  • Tnx,更正了!
  • 另外,你所有的 if 语句在语法上都是不正确的。 (fileperms(file.txt) & 0777) === 0666)你的括号不均匀(共5个)
  • Tnx,再次更正
  • 该代码应该触发多个警告,除非您在任何地方定义了常量filetxt

标签: php file-permissions chmod


【解决方案1】:

事实证明,PHP 会在第一次请求文件权限后缓存它们。调用clearstatcache会重置缓存文件的权限。

当您使用 stat()、lstat() 或受影响函数列表(如下)中列出的任何其他函数时,PHP 会缓存这些函数返回的信息以提供更快的性能。但是,在某些情况下,您可能希望清除缓存的信息。例如,如果在一个脚本中多次检查同一个文件,并且该文件在该脚本的操作期间有被删除或更改的危险,您可以选择清除状态缓存。在这些情况下,您可以使用 clearstatcache() 函数来清除 PHP 缓存的有关文件的信息。

所以这应该在fileperms 调用之间重置缓存。

chmod('file.txt', 0600); 
if ((fileperms('file.txt') & 0777) === 0600) {} // this is true

chmod('file.txt', 0660); 
clearstatcache();
if ((fileperms('file.txt') & 0777) === 0660) {} // this is true

chmod('file.txt', 0666);
clearstatcache(); 
if ((fileperms('file.txt') & 0777) === 0666) {} // this is true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多