php 内容类型 header 无效

php content type header not working

我正在使用标准 LAMP 堆栈托管站点的镜像。尝试 return 生成的图像时,Content-type header 未正确设置为 image/png 而是 returning 为 Content-Type:text/html;字符集=UTF-8。这导致浏览器只显示一堆垃圾而不是图像。我有试图设置 headers 的功能,并在代码中添加了一些我自己的调试,但不知道从这里去哪里。

    // Generate image header
    function Headers() {
        error_log("in Headers function",0);
        // In case we are running from the command line with the client version of
        // PHP we can't send any headers.
        $sapi = php_sapi_name();
        error_log("sapi = $sapi",0);
        if( $sapi == 'cli' ) return;

        // These parameters are set by headers_sent() but they might cause
        // an undefined variable error unless they are initilized
        $file='';
        $lineno='';
        if( headers_sent($file,$lineno) ) {
            error_log("headers already sent",0);
            $file=basename($file);
            $t = new ErrMsgText();
            $msg = $t->Get(10,$file,$lineno);
            die($msg);
        }

        if ($this->expired) {
            error_log("expired",0);
            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
            header("Cache-Control: no-cache, must-revalidate");
            header("Pragma: no-cache");
        }
        header("Content-type: image/$this->img_format");
        header("Custom-header: gnm image/$this->img_format");
        error_log("end of  Headers function, img_format = $this->img_format",0);
    }

通过上面的代码,我得到了错误日志,显示我已经进入了函数,sapi是apache2handler,expired是true,图像格式是png,我在函数的最后。我还正确设置了过期块中的所有 header,并按预期设置了添加的 "Custom-header"。唯一未按预期设置的 header 是 Content-type.

从正在生成然后流式传输图像的 php 文件调用此函数。感谢任何和所有帮助追踪的人。

看起来像我曾经遇到过的问题。 确保您没有将 BOM 添加到您的文件,它会导致 headers 失败,因为它不会是第一个写入文件的东西。

确保您对 header 的调用是将回显给浏览器的第一件事。如果在调用 header 之前回显任何内容,内容类型将自动设置为 text/html.