54

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!

Belgin Fish
  • 17,849
  • 40
  • 101
  • 129

6 Answers6

85

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.

giraff
  • 4,419
  • 2
  • 22
  • 33
robjmills
  • 18,129
  • 15
  • 73
  • 119
  • 8
    This solution is much better as the image headers are passed dynamically. Though I did find one issue with it: in my version of PHP the third line (the header line) was not accepted syntax. This worked though: header("Content-type: ".$imginfo['mime']); – jsleuth Jun 05 '13 at 17:36
  • For those who are receiving the error "the image cannot be displayed" or just an "empty screen". Just start your document with – Fellipe Sanches Sep 11 '20 at 20:17
61
$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="' . $src . '">';
Kristen Waite
  • 1,345
  • 2
  • 15
  • 27
Yaşar Xavan
  • 1,541
  • 1
  • 16
  • 14
36

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

exactly.

Send a header("content-type: image/your_image_type"); and the data afterwards.

Pekka
  • 431,103
  • 135
  • 960
  • 1,075
11

you can do like this :

<?php
    $file = 'your_images.jpg';

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($file));
    echo file_get_contents($file);
?>
11

You can do that, or you can use the readfile function, which outputs it for you:

header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();

Edit: Derp, fixed obvious glaring typo.

Mike Caron
  • 14,031
  • 4
  • 47
  • 76
0

Small edit to @seengee answer: In order to work, you need curly braces around the variable, otherwise you'll get an error.

header("Content-type: {$imginfo['mime']}");

darighteous1
  • 69
  • 1
  • 10