CrushedPixel
CrushedPixel

Reputation: 1172

PHP readfile() returns malfomed file

since today I have a strange problem with my website - I have an API call which proxies an image on the webserver. Code:

<?php
$file = $_GET["id"];

//returns the absolute path to the image
$path = thumb_location($file);

header('Content-Type:image/jpeg');
header('Content-Length: '.filesize($path));

readfile(realpath($path));
?>

This worked perfectly fine until earlier today, when suddenly all of the images are broken. When downloading the image the API call returns and comparing it to the source image, this is the result:

$ cmp -b --print-bytes original.jpg malformed.jpg 
original.jpg malformed.jpg differ: byte 1, line 1 is 377 ?  12 ^J

Any suggestions?

Upvotes: 1

Views: 135

Answers (1)

CrushedPixel
CrushedPixel

Reputation: 1172

After @deceze pointed out that I should inspect the files in a hex editor, I discovered that a line feed character was prepended to the output. This was caused by a newline after the closing ?> tag of a PHP file I recently added. Removing the newline (or the ?> tag) fixed the issue.

Thanks for all your help!

Upvotes: 1

Related Questions