5-minute file cache in PHP

前端 未结 8 1595
醉梦人生
醉梦人生 2020-12-07 17:24

I have a very simple question: what is the best way to download a file in PHP but only if a local version has been downloaded more than 5 minute ago?

In my actual ca

相关标签:
8条回答
  • 2020-12-07 18:07

    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.

    <?php
    
    function 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);
    }
    
    0 讨论(0)
  • 2020-12-07 18:07

    You would warp it into a cache like method:

    function getFile($name) {
        // code stolen from @Peter M
        if ($file exists) {
          if ($file time stamp older than 5 minutes) {
             $file = file_get_contents($url)
          }
        } else {
             $file = file_get_contents($url)
        }
        return $file;
    }
    
    0 讨论(0)
提交回复
热议问题