views:

835

answers:

3

I'm trying to display an image using a PHP script. Basically so the php script is passed on the full path to the image, and it then displays that image in the browser. I've checked to make sure the image exists, it is being read correctly, etc, however in the browser i just see the broken image box (e.g the small red cross in IE) if I go there.

My script sends out these headers:

<?php
header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file)));
header('Content-Type: '.$mime);
header('Content-Length: '.filesize($file)."\n\n");
header('Etag: '.md5($file));
echo $file;
die;

$file contains something like '/var/www/htdocs/images/file.jpg' which works. the $mime is 'image/jpeg'.

I have also tried echoing file_get_contents($file) but it didn't work either.

What is the problem, any thoughts?

+1  A: 

Striving for simplicity...

<?php
header('Content-type:' . mime_content_type($file));
readfile($file);

should function as expected.

Matt
doesn't work :( shows same broken image icon :( typing the url to the image directly in the browser works, and if i type echo readfile($file) and omit the header, i can see the whole lot of gibberish which makes up the image
Click Upvote
No need to type echo readfile() as readfile() writes directly to the output buffer. Adding echo would only pollute the image by echoing the number of bytes returned.
Matt
A: 

I think using imagejpeg and imagecreatefromjpeg will work. Go for something like

$im = imagecreatefromjpeg($file);
imagejpeg($im);

PHP Manual on imagejpeg and imagecreatefromjpeg

abhinavg
+1  A: 

I found the answer, i had some extra whitespace after the ?> tag which was causing the header to not work. grrrrrrr

Click Upvote
I often did this mistake also.. haha
roa3
That's why I've lately stopped using the ending PHP tag...
Henrik Paul
It's common for people not to include the end PHP tag except if there's HTML after it. It's also part of the Zend coding standards. It can create a lot of bugs concerning headers and output.
Jrgns