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?
header('Content-type:image/png'); readfile($fullpath);
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).
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); ?>
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
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With