PHP clearstatcache() Function
The PHP clearstatcache() function clears the file status cache.
PHP caches the information in order to provide faster performance. However, in certain cases, clearing the cached information is required. For example, if the same file is being checked multiple times within a single script, you probably want to avoid caching to get correct results. In these cases, clearstatcache() function is used to clear the information that PHP caches about a file.
The affected functions from this function include:
- stat()
- lstat()
- file_exists()
- is_writable()
- is_readable()
- is_executable()
- is_file()
- is_dir()
- is_link()
- filectime()
- fileatime()
- filemtime()
- fileinode()
- filegroup()
- fileowner()
- filesize()
- filetype()
- fileperms()
Syntax
clearstatcache(clear_realpath_cache, filename)
Parameters
clear_realpath_cache |
Optional. Indicates whether to clear the realpath cache or not. Default is false, which indicates not to clear realpath cache. |
filename |
Optional. Specify a filename, and clears the realpath and stat cache for that file only. Only used if clear_realpath_cache is true. |
Return Value
No value is returned.
Example:
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
In the example below, size of the file is returned at three different stages: initial, after performing write operation and after clearing file status cache. During write operation, the size of the file gets changed. To get the changed file size, clearstatcache() function is used which clears the file status cache.
<?php $file = 'test.txt'; //getting the initial size of the file $file echo "Initial size: ".filesize($file)." bytes\n"; //open the file in write mode $fp = fopen("test.txt", "w"); //write some content to it fwrite($fp, 'A fresh content is added.'); //close the file fclose($fp); //getting the size of the file $file //after write operation echo "After write operation: ".filesize($file)." bytes\n"; //clearing the file status cache clearstatcache(); //getting the size of the file $file //after clearing cache echo "After clearing cache: ".filesize($file)." bytes\n"; ?>
The output of the above code will be:
Initial size: 48 bytes After write operation: 48 bytes After clearing cache: 25 bytes
❮ PHP Filesystem Reference