'; (2) $file = $_GET['file']; $imginfo = getimagesiz...">

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?

+3


source to share


3 answers


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

.

+2


source


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.

0


source


The first example you posted is simple: Output:

<img src="image.png" />

      

The second parameter actually sets the Content-Type:

It returns the content type image/png

or image/jpg

.

I preferred to move on to the second example.

0


source







All Articles