PHP Remote File Cache


/ Published in: PHP
Save to your folder(s)

use this to cache a remote file with xml, json etc


Copy this code and paste it in your HTML
  1. $url = 'http://...';
  2. #we need to do some caching here
  3. $cache_dir = dirname(__FILE__) . '/cache/'; // directory to store the cache
  4. $cache_file = $cache_dir . md5($url);
  5. $cache_time = 24 * 60 * 60; // time to cache file, # minutes * seconds
  6.  
  7. // check the cache_dir variable
  8. if(is_dir($cache_dir) && is_writable($cache_dir) && file_exists($cache_file) && time() - $cache_time < filemtime($cache_file)){
  9. $data = file_get_contents($cache_dir . md5($url)); // name of the cached file
  10. } else {
  11. $data = file_get_contents($url);
  12. file_put_contents($cache_dir . md5($url),$data); //go ahead and cache the file
  13. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.