Friday, January 11, 2013

[Solution] PHP echo function (or print, fputs, etc) adds BOM to the beginning of binary output

I spent more than an hour trying to understand why JPEG image that I get from MySql database is not displayed correctly with PHP code.

Instead of my image, Firefox shows image with "The image ... cannot be displayed because it contains errors." text.

First, I found out that PHP is adding UTF-8 byte order mark (BOM) to the beginning of output.

If I write the same image to file, BOM is not added.

Then I checked my PHP source file, but it does not contain BOM.

And after about an hour I found that it is enough to clean the output buffer with ob_clean function call:

<?php

require_once './include/database.php';

$id = $_GET['id'];

$database = new Database();
$image = $database->getImage($id);

$data = $cover['data'];
$type = $cover['type'];

header("Content-type: $type");

ob_clean();

echo $data;
?>

2 comments:

  1. Thanks a lot Vurdalakov. I spent nearly 8 hours trying to resolve this before I reach here. Your solution worked instantly.

    -- Milind

    ReplyDelete
  2. Thanx from another stressed developer with the same problem! I have spent hours by debugging where exactly the BOM is inserted and how to get rid of it. I don't understand what ob_clean() has to do with it - but it works :-)

    ReplyDelete