Show image using file_get_contents

Belgin Fish picture Belgin Fish · Nov 26, 2010 · Viewed 173.7k times · Source

how can I display an image retrieved using file_get_contents in php?

Do i need to modify the headers and just echo it or something?

Thanks!

Answer

robjmills picture robjmills · Nov 26, 2010

You can use readfile and output the image headers which you can get from getimagesize like this:

$remoteImage = "http://www.example.com/gifs/logo.gif";
$imginfo = getimagesize($remoteImage);
header("Content-type: {$imginfo['mime']}");
readfile($remoteImage);

The reason you should use readfile here is that it outputs the file directly to the output buffer where as file_get_contents will read the file into memory which is unnecessary in this content and potentially intensive for large files.