0

I am trying to display an image file in <img> tag using PHP file handling functions but I'm getting following error instead of an actual image:

image cannot be displayed because it contains errors

Here's my code to read and display the image file:

<?php
header("content-type: image/jpeg");
$filename = "images/sunset.jpg";
$handle = fopen($filename, "rb");
$img= fread($handle, filesize($filename));
fclose($handle);
?>

<img src="<?php echo $img; ?>" alt="image" />

Where I am doing wrong?

Sachin
  • 1,646
  • 3
  • 22
  • 59
  • I voted to reopen this, as the "duplicate question" isn't a duplicate. You are asking about serving up content type `image/jpeg`, not `text/html`. – delboy1978uk Sep 03 '18 at 10:18
  • Think about it: For a normal image, do you open the image file in an editor, and then copy & paste the _binary contents_ of that image file into the `src` attribute of an HTML `img` element? No? Because that’s effectively what your script is doing here. – misorude Sep 03 '18 at 10:23
  • Actually delboy's answer is pretty much correct. But do you really need to fopen an image in PHP? That just sounds a bit weird to me. Since what's the difference between accessing your PHP script and the file directly? – maio290 Sep 05 '18 at 10:01

1 Answers1

0

You are simply sending the wrong stuff. You declare a content type of image\jpeg, then proceed to return HTML markup.

Get rid of the HTML and just echo $img;

delboy1978uk
  • 12,118
  • 2
  • 21
  • 39