Cached, PHP generated Thumbnails load slowly

前端 未结 19 2094
醉酒成梦
醉酒成梦 2020-12-12 11:35

Question Part A ▉ (100 bountys, awarded)
Main question was how to make this site, load faster. First we needed to read these waterfalls. Thanks all fo

19条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 12:10

    I am far from an expert but...

    In regards to this: "An If-Modified-Since conditional request returned the full content unchanged." and my comments.

    The code used to generate the Thumbnails should be checking for the following:

    1. Is there a cached version of the thumbnail.
    2. Is the cached version newer than the original image.

    If either of these are false the thumbnail should be generated and returned no matter what. If they are both true then the following check should be made:

    1. Is there a HTTP_IF_MODIFIED_SINCE header
    2. Is the cached version's last modified time the same as the HTTP_IF_MODIFIED_SINCE

    If either of these are false the cached thumbnail should be returned.

    If both of these are true then a 304 http status should be returned. I'm not sure if its required but I also personally return the Cache-Control, Expires and Last-Modified headers along with the 304.

    In regards to GZipping, I've been informed that there is no need to GZip images so ignore that part of my comment.

    Edit: I didn't notice your addition to your post.

    session_cache_limiter('public');
    header("Content-type: " . $this->_mime);
    header("Expires: " . gmdate("D, d M Y H:i:s", time() + 2419200) . " GMT");
    // I'm sure Last-Modified should be a static value. not dynamic as you have it here.
    header("Last-Modified: " . gmdate("D, d M Y H:i:s",time() - 404800000) . " GMT");
    

    I'm also sure that your code needs to check for the HTTP_IF_MODIFIED_SINCE header and react to it. Just setting these headers and your .htaccess file won't provide the required result.

    I think you need something like this:

    $date = 'D, d M Y H:i:s T'; // DATE_RFC850
    $modified = filemtime($filename);
    $expires = strtotime('1 year'); // 1 Year
    
    header(sprintf('Cache-Control: %s, max-age=%s', 'public', $expires - time()));
    header(sprintf('Expires: %s', date($date, $expires)));
    header(sprintf('Last-Modified: %s', date($date, $modified)));
    header(sprintf('Content-Type: %s', $mime));
    
    if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
        if(strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) === $modified) {
            header('HTTP/1.1 304 Not Modified', true, 304);
            // Should have been an exit not a return. After sending the not modified http
            // code, the script should end and return no content.
            exit();
        }
    }
    // Render image data
    

提交回复
热议问题