首页 > 解决方案 > 在 PHP 中多次获取文件权限似乎不起作用

问题描述

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

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显示不同的值。是否发生了一些缓存?

标签: phpfile-permissionschmod

解决方案


事实证明,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


推荐阅读