Make PHP page return “304 Not Modified” if it hasn't been modified

前端 未结 4 810
有刺的猬
有刺的猬 2020-12-17 03:33

I have a PHP file that will return the same thing with the same $_GET parameters every time -- it\'s deterministic.

Unfortunately for efficiency (this file is reques

4条回答
  •  旧巷少年郎
    2020-12-17 04:37

    This script will render the whole PHP Script again, but after that, it checks if the ETag ist equivalent to the MD5 of the output string and if so, it sends a 304 and no bandwith is used. You could also create such a thing with the MD5 of all the QueryString etc. and store it somewhere, you would not need to recreate the output content (even faster)

    function sanitize_output($buffer) {
        $headers = apache_request_headers();
        $tt5=md5($buffer);  
        header('ETag: '.$tt5);
        if (isset($headers['If-None-Match']) && $headers['If-None-Match']===$tt5) {
            header('HTTP/1.1 304 Not Modified');
            header('Connection: close');
            exit();
        }
        return $buffer;
    }
    
    ob_start("sanitize_output");
    

提交回复
热议问题