Handling If-modified-since header in a PHP-script

后端 未结 2 951
逝去的感伤
逝去的感伤 2020-11-30 04:55

I have a PHP script which is called with an ?img= parameter.

The value for that parameter is an (urlencoded) URL of an image.

My script chec

2条回答
  •  没有蜡笔的小新
    2020-11-30 05:48

    I recently had to use this feature (serving image via PHP) in order to make images visible only for registered users. Jack's code was helpful, but I had to do a few hacks for it to work perfectly. Thought I should share this one.

    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && 
        strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($path_to_image))
    {
        header('HTTP/1.0 304 Not Modified');
        header("Cache-Control: max-age=12096000, public");
        header("Expires: Sat, 26 Jul 2015 05:00:00 GMT");
        header("Pragma: cache");
        exit;
    }else{
        header("Content-type: image/jpeg");
        header("Cache-Control: max-age=12096000, public");
        header("Expires: Sat, 26 Jul 2015 05:00:00 GMT");
        header("Pragma: cache");
        echo file_get_contents($path_to_image);
    }
    

    In short, the script returns Not Modified if it's a browser request HTTP_IF_MODIFIED_SINCE. Otherwise, the image is served with appropriate headers and expiry dates.

提交回复
热议问题