PHP image in browser
(1)
$file = $_GET['file'];
echo '<img src="'.$file.'" />';
(2)
$file = $_GET['file'];
$imginfo = getimagesize($file);
header('Content-type: '.$imginfo['mime']);
echo file_get_contents($file);`
From these two codes, my image can render well in the browser. But what are their differences? Which method should I prefer?
source to share
The first example you posted just "includes" the image file in the DOM. This will essentially output something like:
<img src="path/to/image.png" />
Whereas the second parameter actually sets Content-Type
to the mime
image value . The value, if it is png
, for example, the page that runs this script will actually render as a whole image.
If it was a png image, it will return the content type image/png
.
source to share
The key difference is inferred:
The example 1
links from the path, whereas the example 2
outputs the binary and calls it an image (so HTTP clients can interpret the response correctly).
To the point ... the example 1
is preferred as it doesn't need to keep the file contents in memory.
source to share