1

I want my PHP to output a simple image but when I do it gives me a white square, so I thought the IMG couldn't be found but when I put a simple HTML IMG tag it can be found the code is very simple. also if I try an image from the internet it also won't work.

<!--testing if image can be found-->
<!--<img src="img.jpeg">-->
<?php

header("Content-type: image/jpeg");
readfile("img.jpeg");
exit(0);
?>
Ludo.Snel
  • 15
  • 4

2 Answers2

4

Basically what's happening here is that you output some HTML comments before you output the image which means your image file is invalid and so your internet browser doesn't know what to display and defaults to what you're seeing (a white box in the middle of your screen).

Additionally when you use header you should ensure that you haven't already returned data!

If you check your source in your browser you'll see something like...

<!--testing if image can be found-->
<!--<img src="img.jpeg">-->
ÿØÿàJFIFÿá‹rExifII*Àж..................................

...with the additioonal data continuing for some time!

If you remove the comments from your PHP file then it will work as intended; your (entire) file should look something like:

<?php    
header("Content-type: image/jpeg");
readfile("img.jpeg");

Note: You may want to add additional headers RE content length etc. but these aren't strictly necessary for most browsers.

Steven
  • 6,053
  • 2
  • 16
  • 28
  • 1
    I'm pretty certain that @Steven has nailed your problem here. Just because you don't see the comments a browser, doesn't mean they're not being sent. – Ben Hillier Apr 07 '21 at 15:19
1

To display an image using content type header, you must put only php on the page. If you add any other content it'll display a blank square

ex.

<?php header("Content-type: image/png"); readfile("./resources/img/favicon.png"); ?>
tycyly
  • 249
  • 1
  • 14