【问题标题】:php content type header not working [duplicate]php内容类型标头不起作用[重复]
【发布时间】:2015-12-22 15:53:08
【问题描述】:

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

    // 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,过期是真的,图像格式是 png,并且我在函数的末尾。我还正确设置了过期块中的所有标题,并且添加的“自定义标题”按预期设置。唯一未按预期设置的标头是 Content-type。

这个函数是从一个生成然后流式传输图像的 php 文件中调用的。感谢您提供任何和所有帮助追踪此问题。

【问题讨论】:

    标签: php http-headers content-type


    【解决方案1】:

    看起来像我曾经遇到过的问题。 确保不要将 BOM 添加到文件中,这会导致标题失败,因为它不会是文件中写入的第一件事。

    【讨论】:

    • 这是基本页面中的问题,但不是生成图像的页面中的问题。
    【解决方案2】:

    确保您对 header 的调用是最先回显到浏览器的内容。如果在调用 header 之前回显了任何内容,则内容类型会自动设置为 text/html

    【讨论】:

    • 原来在标题调用之前页面上有一些内容。我从 html 中删除了空格,图像现在按预期返回。
    猜你喜欢
    • 2013-08-21
    • 1970-01-01
    • 2014-04-22
    • 2010-09-30
    • 2017-07-22
    • 2021-08-25
    • 2016-05-17
    • 2017-09-18
    • 2016-06-19
    相关资源
    最近更新 更多