-1

When calling the PHP function fileperms multiple times, it seems that the file permissions are not shown correctly anymore:

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

The permissions are changed on the files, but the call to fileperms shows a different value. Is there some caching happening?

Daan
  • 7,685
  • 5
  • 43
  • 52

1 Answers1

0

It turns out that PHP caches the file permissions after the first time they are requested. Calling clearstatcache will reset the cached file permissions.

When you use stat(), lstat(), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the clearstatcache() function to clear the information that PHP caches about a file.

So this should reset the cache in between the fileperms calls.

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

Daan
  • 7,685
  • 5
  • 43
  • 52