-2

I have this code but when I used it page show error => headers already sent by. Please show mer how to fix this page! Than you!

<!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>
user3577947
  • 277
  • 2
  • 3
  • 12
  • 1
    You should put the `header(..)` at the top of the page. – Joren Apr 27 '14 at 10:02
  • Why are you even setting the content type as image/jpeg when you're clearly outputting HTML? I think these need to be two separate requests. Are you trying to embed the image in the page? – thexacre Apr 27 '14 at 10:33

2 Answers2

0

You can not output anything before you set header() and you can not mix an html page with an image in one document. Separate the two and include the image (meaning image data and image header before outputting the data) as a

Clarence
  • 2,944
  • 18
  • 16
0

Server response usually looks like this:

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>

As you can see at first place are headers and after headers comes HTML content. In your case the server response is more like this:

  1. Headers
  2. Content
  3. Headers
  4. Content

The headers sent at point 3. are caused by this line header('Content-type: image/jpeg');. Solution to this problem is to always send your headers before any output, for example this is alright:

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

This is not alright and will cause the "headers already sent" error:

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