silkfire
silkfire

Reputation: 26033

Does file_get_contents use a cache?

I have a function that generates a table with contents from the DB. Some cells have custom HTML which I'm reading in with file_get_contents through a templating system.

The small content is the same but this action is performed maybe 15 times (I have a limit of 15 table rows per page). So does file_get_contents cache if it sees that the content is the same?

Upvotes: 9

Views: 22145

Answers (3)

David Spector
David Spector

Reputation: 1677

The correct answer is yes. All the PHP file system functions do their own caching, and you can use the "realpath_cache_size = 0" directive in PHP.ini to disable the caching if you like. The default caching timeout is 120 seconds. This is separate from the caching typically done by browsers for all GET requests (the majority of Web accesses) unless the HTTP headers override it. Caching is not a good idea during development work, since your code may read in old data from a file whose contents you have changed.

Upvotes: 4

Raptor
Raptor

Reputation: 54258

file_get_contents() does not have caching mechanism. However, you can use write your own caching mechanism.

Here is a draft :

$cache_file = 'content.cache';
if(file_exists($cache_file)) {
  if(time() - filemtime($cache_file) > 86400) {
     // too old , re-fetch
     $cache = file_get_contents('YOUR FILE SOURCE');
     file_put_contents($cache_file, $cache);
  } else {
     // cache is still fresh
  }
} else {
  // no cache, create one
  $cache = file_get_contents('YOUR FILE SOURCE');
  file_put_contents($cache_file, $cache);
}

UPDATE the previous if case is incorrect, now rectified by comparing to current time. Thanks @Arrakeen.

Upvotes: 9

Nate Lampton
Nate Lampton

Reputation: 349

Like @deceze says, generally the answer is no. However operating system level caches may cache recently used files to make for quicker access, but I wouldn't count on those being available. If you'd like to cache a file that is being read multiple times per request, consider using a static variable to act as a cache inside a wrapper function.

function my_file_read($filename) {
  static $file_contents = array();
  if (!isset($file_contents[$filename])) {
    $file_contents[$filename] = file_get_contents($filename);
  }
  return $file_contents[$filename];
}

Calling my_file_read($filename) multiple times will only read the file from disk a single time, subsequent calls will read the value from the static variable within the function. Note that you shouldn't count on this approach for large files or ones used only once per page, since the memory used by the static variable will persist until the end of the request. Keeping the contents of files unnecessarily in static variables is a good way to make your script a memory hog.

Upvotes: 4

Related Questions