PHP – clearstatcache() Explained

For the functions like is_file(), file_exists(), etc PHP caches the result of this function for each file for faster performance if function called again.

But in some cases you want to clear this cached information, for the task like getting the information of the same file multiple times in same page.
Points to be note that, PHP also cache the information of the files which not exists. So when you use file_exists() on file which is not exists. PHP will return FALSE untill you create that file.

After creating this file PHP will return TRUE. But when you delete this file manually and call the file_exists() on that file will return TRUE. Because PHP will return the cached informarion.

So always use the unlink() because unlink() will remove the cache of that file automatically.

For clearing the file state cache, clearstatcache() function is used. This function will clear the all cache information stored with below list of functions.
stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), and fileperms().

Here is the example taken from the PHP Manual:

 $file = "sample.txt";

function get_owner($file)
 $stat = stat($file);
 $user = posix_getpwuid($stat["uid"]);
 return $user["name"];

$format = "UID @ %s: %s\n";

printf($format, date("r"), get_owner($file));

chown($file, "ross");
 printf($format, date("r"), get_owner($file));


 printf($format, date("r"), get_owner($file));

UID @ Sun, 12 Oct 2009 21:48:28 +0100: root
UID @ Sun, 12 Oct 2009 21:48:28 +0100: root
UID @ Sun, 12 Oct 2009 21:48:28 +0100: ross

Leave a Reply

Your email address will not be published. Required fields are marked *