title: Getting image from MySQL in PHP results in damaged image
body: <p>I'm stuck with the error </p>
  
  <blockquote>
    <p>"The image “....image.php?id=1878” cannot be displayed because it contains errors.</p>
  </blockquote>
  
  <p>This is the code I am retrieving the image content from the db. The data in db is correct, because the same file displays perfectly with some old php code. In fact, the code I use is the same exact old code, I just extracted it from many linked(included) php files and obviously I am missing something.</p>
  
  <pre><code>$query="SELECT image_original_file, mime_type, {$field_content} as content, {$field_content}_md5 as imhash, CHAR_LENGTH({$field_content}) as leng  FROM IMAGES WHERE ID_image={$_GET['id']}";
  $res=mysql_query($query,DB_CON);
  $myRow = mysql_fetch_row($res);
  //Of course this echo statement is just for debuging, as echo causes the default headers to be sent.
  echo "Fetched content length:".mb_strlen($myRow[2])." and MySQL length ".$myRow[4];
  list($name,$type,$content,$imhash,$length)=$myRow;
  </code></pre>
  
  <p>The output here shows that the content length in php is 29179bytes, but in MySQL it is 28605 (which is the correct size when I save the image).
  I wonder why the size of the content is different in PHP after those lines of code. The filecontent in DB is not base64 encoded, nor does the original code use any manipulation on the content retrieved from the db. I compared the Headers of the old code and the "new" code, everything except the content length is the same. I suspect this ia some sort of characterset problem? </p>
  
  <p>I tried:</p>
  
  <pre><code> mysql_set_charset('utf8',$con);
   mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", DB_CON);
   mysql_query("SET NAMES utf8",DB_CON);
  </code></pre>
  
  <p>But the problem persists. I will be very happy for some advice.</p>
  
  <p>The image is sent to the browser like this:</p>
  
  <pre><code>header("ETag: \"{$imhash}\"");
  header("Expires: " . gmdate("D, d M Y H:i:s") . " GMT");
  header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  header("Cache-Control: must-revalidate");
  header("Accept-Ranges: bytes");
  header("Content-Length: ".mb_strlen($content));
  header("Content-Type: {$type}");
  header("Content-Disposition: inline; filename=\"{$name}\";");
  echo $content;
  </code></pre>