Clears cached filesystem stat information so a subsequent check can observe recent changes.
What It Does and When to Use It
Refresh stat and realpath caches for a specific file. APCu stores local application data, Redis is external and can be shared among hosts, and OPcache stores compiled code.
Requirements, Inputs and Expected Behavior
Confirm the runtime, extension, environment variables, and permissions before running the examples in production. The stat cache and PHP realpath cache are distinct; use the clear_realpath_cache flag when appropriate.
Example 1: Basic Operation
Refresh stat and realpath caches for a specific file.
<?php
$path = __FILE__;
$sizeBefore = filesize($path);
clearstatcache(true, $path);
$sizeAfter = filesize($path);
echo "$sizeBefore -> $sizeAfter";
Example 2: Behavior and Validation
Check metadata after another process may have modified a file.
<?php
$path = __DIR__ . '/report.csv';
clearstatcache(false, $path);
if (is_file($path)) echo filemtime($path);
Practical Example: Application Use
Use a temporary fixture to observe a metadata change.
<?php
$file = tempnam(sys_get_temp_dir(), 'stat-');
file_put_contents($file, 'one');
$a = filesize($file);
file_put_contents($file, 'updated content');
clearstatcache(false, $file);
$b = filesize($file);
unlink($file);
echo "$a to $b";
Important Behavior and Edge Cases
The second example highlights: Check metadata after another process may have modified a file. The practical example adds: Use a temporary fixture to observe a metadata change.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| APCu versus Redis and OPcache | APCu stores local application data, Redis is external and can be shared among hosts, and OPcache stores compiled code. |
| Choosing safely | Define TTL, invalidation, and concurrency behavior separately from the cache storage API. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming a cache is shared across multiple servers | Confirm process- and host-level cache scope; use a distributed store when needed. |
| Never invalidating cached data | Set a TTL or versioned cache key and test release-time invalidation. |
| Skipping operational constraints | The stat cache and PHP realpath cache are distinct; use the clear_realpath_cache flag when appropriate. |
Key Takeaways
- Clears cached filesystem stat information so a subsequent check can observe recent changes.
- Use a temporary fixture to observe a metadata change.
- Define TTL, invalidation, and concurrency behavior separately from the cache storage API.