Reputation: 1101
(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 2 code, my image can show in the browser nicely. But what is the differences of them? Which method should I prefer?
Upvotes: 3
Views: 150
Reputation: 11
The first example you've posted is simply: output:
<img src="image.png" />
The second option actually sets the Content-Type:
It's return the content type of image/png
or image/jpg
like that.
I prefered go to second example.
Upvotes: 0
Reputation: 5731
The key difference is output:
Example 1
references from a path whereas example 2
outputs the binary and labels it an image (so HTTP clients can interpret the response correctly).
To the point... example 1
is preferred because it doesn't have to store the file contents in memory.
Upvotes: 0
Reputation: 13128
The first example you've posted is simply "including" the image file into the DOM. It would essentially output something like:
<img src="path/to/image.png" />
While the second option actually sets the Content-Type
to whatever the mime
of the image is. Meaning if it's a png
for example, the page that runs that script will actually be served as a whole image.
If it was a png image, it'd return the content type of image/png
.
Upvotes: 2