views:

1378

answers:

2

I am trying to read a image file (.jpeg to be exact), and 'echo' it back to the page output, but have is display an image...

my index.php has an image link like this:

<img src='test.php?image=1234.jpeg' />

and my php script does basically this:

1) read 1234.jpeg 2) echo file contents... 3) I have a feeling I need to return the output back with a mime-type, but this is where I get lost

Once I figure this out, I will be removing the file name input all together and replace it with an image id.

If I am unclear, or you need more information, please reply.

+11  A: 

The PHP Manual has this example:

<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;
?>

The important points is that you must send a Content-Type header. Also, you must be careful not include any extra white space (like newlines) in your file before or after the <?php ... ?> tags.

Martin Geisler
It's easier to omit optional ?> tag at the end of the file.
Gleb
To that end, some (including Zend, PEAR, or both -- I forget) recommend omitting the closing ?>. It's perfectly syntactically valid, and guarantees no issues with trailing whitespace.
Frank Farmer
But, but... it's weird not to close what one open's :-)
Martin Geisler
Don't omit the ?>. "Easier" doesn't mean "better".
Jared Farrish
Totaly agree with Frank Farmer, a code without the ending ?> will be easier to debug.It's just a really useful tip.And to answer to Jared Farrish, easier here do mean better, it's right, and it should be used everywhere, since your code should not be bugged or anything, if you don't put it, it will advert you if there are some errors.It saves a lot of debugging times.
Boris Guéry
agreed, omit it. Technically it's more correct, because we don't want the PHP parsing to ever end on the script in question.
William Denniss
A: 

Another easy Option (not any better, just different) if you aren't reading from a database is to just use a function to output all the code for you... Note: If you also wanted php to read the image dimensions and give that to the client for faster rendering, you could easily do that too with this method.

<?php
  Function insertImage( $fileName ) {
    echo '<img src="path/to/your/images/',$fileName,'">';    
  }
?>

<html>
  <body>
    This is my awesome website.<br>
    <?php insertImage( '1234.jpg' ); ?><br>
    Like my nice picture above?
  </body>
</html>
Joe Bubna