Output an Image in PHP


Question

I have an image $file ( eg ../image.jpg )

which has a mime type $type

How can I output it to the browser?

1
66
4/13/2015 3:25:20 PM

Accepted Answer

$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);
129
12/5/2009 10:46:03 AM

If you have the liberty to configure your webserver yourself, tools like mod_xsendfile (for Apache) are considerably better than reading and printing the file in PHP. Your PHP code would look like this:

header("Content-type: $type");
header("X-Sendfile: $file"); # make sure $file is the full path, not relative
exit();

mod_xsendfile picks up the X-Sendfile header and sends the file to the browser itself. This can make a real difference in performance, especially for big files. Most of the proposed solutions read the whole file into memory and then print it out. That's OK for a 20kbyte image file, but if you have a 200 MByte TIFF file, you're bound to get problems.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon