5-minute file cache in PHP 5-minute file cache in PHP curl curl

5-minute file cache in PHP


Use a local cache file, and just check the existence and modification time on the file before you use it. For example, if $cache_file is a local cache filename:

if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * 5 ))) {   // Cache file is less than five minutes old.    // Don't bother refreshing, just use the file as-is.   $file = file_get_contents($cache_file);} else {   // Our cache is out-of-date, so load the data from our remote server,   // and also save it over our cache for next time.   $file = file_get_contents($url);   file_put_contents($cache_file, $file, LOCK_EX);}

(Untested, but based on code I use at the moment.)

Either way through this code, $file ends up as the data you need, and it'll either use the cache if it's fresh, or grab the data from the remote server and refresh the cache if not.

EDIT: I understand a bit more about file locking since I wrote the above. It might be worth having a read of this answer if you're concerned about the file locking here.

If you're concerned about locking and concurrent access, I'd say the cleanest solution would be to file_put_contents to a temporary file, then rename() it over $cache_file, which should be an atomic operation, i.e. the $cache_file will either be the old contents or the full new contents, never halfway written.


Try phpFastCache , it support files caching, and you don't need to code your cache class. easy to use on shared hosting and VPS

Here is example:

<?php// change files to memcached, wincache, xcache, apc, files, sqlite$cache = phpFastCache("files");$content = $cache->get($url);if($content == null) {     $content = file_get_contents($url);     // 300 = 5 minutes      $cache->set($url, $content, 300);}// use ur $content hereecho $content;


Here is a simple version which also passes a windows User-Agent string to the remote host so you don't look like a trouble-maker without proper headers.

<?phpfunction getCacheContent($cachefile, $remotepath, $cachetime = 120){    // Generate the cache version if it doesn't exist or it's too old!    if( ! file_exists($cachefile) OR (filemtime($cachefile) < (time() - $cachetime))) {        $options = array(            'method' => "GET",            'header' => "Accept-language: en\r\n" .            "User-Agent: Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)\r\n"        );        $context = stream_context_create(array('http' => $options));        $contents = file_get_contents($remotepath, false, $context);        file_put_contents($cachefile, $contents, LOCK_EX);        return $contents;    }    return file_get_contents($cachefile);}