Valid images displayed by PHP always "contain errors", what could be the reason for this?

A few months ago I wrote a website for a client using PHP 5.3. It works fine on my own LAMP web server. However, when he tried to install it on his own server (currently an OVH server running DirectAdmin on CentOS 5), he had a problem that I found difficult to figure out.

A website can store images uploaded through forms. Images are watermarked on upload and moved to a directory on the web server (some metadata is stored in the database, but this is not related to this problem).

To return these images to the user, the script is used like this:

header("Content-type: image/jpeg");
ob_start();
echo file_get_contents($path);
$size = ob_get_length();
$img = ob_get_contents();
ob_end_clean();
header ("Content-length: " . $size);
echo $img;

Unfortunately, this always returns a broken image (in Firefox, “The image cannot be displayed because it contains errors”). Now, after rigorous testing, I know that:

  • Images upload correctly to the server. The image data stored on the web server is valid and can be obtained via FTP as a normal image.

  • If I store $ img in the file immediately before the last line of the previous script, for example:

    $fh = fopen("test.jpg", "w");
    fwrite($fh, $img);
    fclose($fh);
    

    It will also save the correct image data in a file. Thus, the data is not corrupted immediately before being sent to a user’s web browser.

  • Headers are sent correctly.

! / , /jpeg, , , ( apache ). EXIF. , PHP, -, JFIF ( JPEG), -.

, PHP Apache, , , - . - -, ?

EDIT:

script :

$img = file_get_contents($path);
$size = filesize($path);

, , , PHP. , - gzip. ?

+5
3

, - ( , , , ) PHP .
, .

?

header("Content-type: image/jpeg");
echo file_get_contents($path);

?

header("Content-type: image/jpeg");
readfile($path);

( wget " " ) .

. ob . - (!)

header("Content-type: image/jpeg");
header ("Content-length: " . filesize($path));
readfile($path);
+3

-, , , jpeg, - . , , , jpeg -jpeg.

-, ob_start() .

-, Content-length, , , .

, GD , .

ob_start();
$image = imagecreatefromjpeg( $path );
if (!$image ) {
    // error trapping / other logic here
}
ob_end_clean();
header( "Content-type: image/jpeg" );
@imagejpeg( $image );
if ( $image ) {
    imagedestroy( $image );
}
+1

, , , :

"ha!, ! UTF-8 - ! PHP script. "

, , - , php readfile file_get_contents.

Protected

I solved this by changing the encoding of the page on which the code is posted. UTF-8 seems ok, but the BOM (Byte Order Mask) should go. How you change this depends on the software you use for editing. I am using an old version of Dreamweaver, in which I can uncheck the box using the specification in the "Page Properties" section.

+1
source

All Articles