Our blog

 

PHP Cached Download Function

If you are coding a PHP script to deal with big files, it makes sense to build in some kind of caching logic so that your script won't download the same file every single time it is run, but will check to see how long ago it last downloaded that file and only download it again if it is more than a certain timeframe old.

This function allows you to do exactly that - check it out:

PHP:
  1. $cache_days = 1;
  2.  
  3. $cache_days = $cache_days * (24*60*60);
  4.  
  5. function cached_download($remote, $local){
  6. $cache_days = $GLOBALS['cache_days'];
  7. if(file_exists($local) && (filemtime($local)> (time() - $cache_days))){
  8. // we have a local copy that is less than $cache_days old
  9. <h3>Using Cached - Last Downloaded ' . date('H:m:s d/m/Y', filemtime($local) . '</h3>
  10. ';
  11. }else{
  12. <h3>Downloading Now...</h3>
  13. ';
  14. copy($remote, $local);
  15. }
  16. }

More Reading:

 

Leave a Reply