284 of 410 menu

The clearstatcache Function

The clearstatcache function clears the cache that stores information about file status. PHP caches the results of file handling functions such as filesize, filemtime, and others. This function is useful when you need to get up-to-date data about a file that may have changed during script execution.

Syntax

clearstatcache([bool $clear_realpath_cache = false], [string $filename = null]);

Example

Simplest example of using the function without parameters:

<?php clearstatcache(); echo 'File cache cleared'; ?>

Code execution result:

'File cache cleared'

Example

Example with clearing cache for a specific file:

<?php $file = 'test.txt'; clearstatcache(true, $file); echo 'Cache cleared for file: ' . $file; ?>

Code execution result:

'Cache cleared for file: test.txt'

Example

Practical example with getting file size:

<?php $file = 'data.txt'; // First getting the size $size1 = filesize($file); // Modify the file (in real code the file could have been modified by another process) file_put_contents($file, 'new content', FILE_APPEND); // Second getting the size without clearing cache $size2 = filesize($file); // Clear cache and get actual size clearstatcache(true, $file); $size3 = filesize($file); echo "Size1: $size1, Size2: $size2, Size3: $size3"; ?>

Code execution result:

'Size1: 10, Size2: 10, Size3: 20'

See Also

  • the file_exists function,
    which checks file existence
  • the filesize function,
    which returns file size
  • the filemtime function,
    which returns modification time
byenru