How to avoid a possible missing cache file in PHP?

I have a simple caching system as

if (file_exists($cache)) {
echo file_get_contents($cache);
// if coming here when $cache is deleting, then nothing to display
else {
// PHP process

We regularly delete outdated cache files, e.g. deleting all caches after 1 hour. Although this process is very fast, but I am thinking that a cache file can be deleted right between the if statement and file_get_contents processes.

I mean when if statement checks the existence of cache file, it exists; but when file_get_contents tries to catch it, it is no longer there (deleted by simultaneous cache deleting process).

file_get_contents locks the file to avoid the undergoing delete process during the read process. But the file can be deleted when the if statement sends the PHP process to the first condition (before start of the file_get_contents).

Is there any approach to avoid this? Is the cache deleting system different?

NOTE: I did not face any practical problem, as it is not very probable to catch this event, but logically it is possible, and should happen on heavy loads.

Leave a Reply


Hire Me
Follow Me!
Most Popular Articles & Pages
Because your vote is Important
Sorry, there are no polls available at the moment.