Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, display image with Header()

Tags:

php

header

I'm displaying images from outside my web root, like this:

header('Content-type:image/png'); readfile($fullpath); 

The content-type: image/png is what confuses me.

Someone else helped me out with this code, but I noticed that not all images are PNG. Many are jpg or gif.
And still they are displayed successfully.

does anyone know why?

like image 304
coffeemonitor Avatar asked Apr 13 '10 23:04

coffeemonitor


People also ask

How to put image in header in PHP?

header('Content-type:image/png'); readfile($fullpath);

What does header () do in PHP?

The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request).

How do I change the content-type header to an image PNG?

php header ('Content-Type: image/png'); $im = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream'); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color); imagepng($im); imagedestroy($im); ?>


2 Answers

The best solution would be to read in the file, then decide which kind of image it is and send out the appropriate header

$filename = basename($file); $file_extension = strtolower(substr(strrchr($filename,"."),1));  switch( $file_extension ) {     case "gif": $ctype="image/gif"; break;     case "png": $ctype="image/png"; break;     case "jpeg":     case "jpg": $ctype="image/jpeg"; break;     case "svg": $ctype="image/svg+xml"; break;     default: }  header('Content-type: ' . $ctype); 

(Note: the correct content-type for JPG files is image/jpeg)

like image 69
paullb Avatar answered Oct 14 '22 23:10

paullb


There is a better why to determine type of an image. with exif_imagetype

If you use this function, you can tell image's real extension.

with this function filename's extension is completely irrelevant, which is good.

function setHeaderContentType(string $filePath): void {     $numberToContentTypeMap = [         '1' => 'image/gif',         '2' => 'image/jpeg',         '3' => 'image/png',         '6' => 'image/bmp',         '17' => 'image/ico'     ];      $contentType = $numberToContentTypeMap[exif_imagetype($filePath)] ?? null;          if ($contentType === null) {         throw new Exception('Unable to determine content type of file.');     }      header("Content-type: $contentType"); } 

You can add more types from the link.

Hope it helps.

like image 37
aliqandil Avatar answered Oct 14 '22 22:10

aliqandil