I've encountered a really strange bug I've been trying to resolve for the past few days unsuccessfully. I have a class for caching API calls, and a class used in a WordPress plugin to create custom API endpoints. In a nutshull the WordPress plugin hits an external API and caches the results with my caching class. Many individual items are accessed with the api, resulting in a few dozen local cache files.
The scenario
In my caching class, if a local cache has expired (it's older than the expiration time set on instantiation), the API gets hit again and results get cached as such:
file_put_contents($this->cache, $this->data, LOCK_EX);
In my WordPress plugin I want to loop through the cache files and remove any that haven't been accessed for N days. This method gets hit using cron. I'm checking the accessed time as such (this is still in development, printing for debug):
print($file . ': ' . date('F jS Y - g:i:s A', fileatime(UPLOADS_DIR . '/' . $file)));
Here's the full method so far:
public static function cleanup_old_caches($days = 30) {
// Get the files
$files = scandir(UPLOADS_DIR);
// Save out .txt files
$cache_files = array();
// Loop through everything
foreach ( $files as $file ) {
if ( strstr($file, '.txt') ) {
$cache_files[] = $file;
}
}
// Loop through the cache files
foreach ( $cache_files as $file ) {
clearstatcache();
print($file . ': ' . date('F jS Y - g:i:s A', fileatime(UPLOADS_DIR . '/' . $file)));
echo "\n";
clearstatcache();
}
return '';
}
You'll note I have a few clearstatcache()
calls at the moment.
The problem
Any time a new cache file gets created, the accessed time as reported by fileatime()
for many other files in the same directory gets updated to the current time. These sometimes say a second after the new cache file.
Here's my full method:
private function hit_api() {
// Set the return from the API as the data to use
$this->data = $this->curl_get_contents($this->api_url);
// Store the API's data for next time
file_put_contents($this->cache, $this->data, LOCK_EX);
}
I can find another way to write my cleanup logic, but I'm concerned that PHP is actually touching each of these files (I've seen 12 out of 18 for one new file).
Things I've tried
clearstatcache()
calls absolutely _everywhere)- Manually doing all the
fopen()
,fwrite()
,fflush()
,fclose()
steps manually - Writing the file names being written at the point of the
file_put_contents()
call
If anybody has an idea what's going on here I'll be muuuch appreciative.