错误:“已发送标头”

时间:2014-04-27 10:01:14

标签: php

我有这段代码,但是当我使用它时,页面显示错误=>已经发送的标头。 请告诉我如何修复此页面!比你!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head></head>
    <table border="1px">
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
    <tr><td>3</td></tr>
    <tr><td>
    <?
        $dbname = 'mongo';
        $m = new Mongo("mongodb://127.0.0.1:10000/mongo");
        $db = $m->$dbname;

        $gridFS = $db->getGridFS();
        $id = 123;

        header('Content-type: image/jpeg');
        echo $data= $gridFS->findOne(array("_id" => $id))->getBytes();   
    ?>
    </td></tr>
    </table>
    </body>
    </html>

2 个答案:

答案 0 :(得分:0)

在设置header()之前无法输出任何内容,并且无法将html页面与图像混合在一个文档中。将两者分开并将图像(在输出数据之前表示图像数据和图像头)包括在内

答案 1 :(得分:0)

服务器响应通常如下所示:

HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
ETag: "3f80f-1b6-3e1cb03b"
Content-Type: text/html; charset=UTF-8
Content-Length: 131
Accept-Ranges: bytes
Connection: close

<html>
<head>
  <title>An Example Page</title>
</head>
<body>
  Hello World, this is a very simple HTML document.
</body>
</html>

正如您在第一时间看到的那样,标题和标题后面是HTML内容。在您的情况下,服务器响应更像是这样:

  1. 接头
  2. 内容
  3. 标题
  4. 内容
  5. 第3点发送的标头是由此行header('Content-type: image/jpeg');引起的。解决此问题的方法是始终在任何输出之前发送标头,例如这是正常的:

    <? header('Content-type: image/jpeg'); ?>
    <html></html>
    

    这不正常,会导致&#34;标头已经发送&#34;错误:

    <html></html>
    <? header('Content-type: image/jpeg'); ?>