Show image using file_get_contents

PhpHttp HeadersFile Get-Contents

Php Problem Overview


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!

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

$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 . '">';

Solution 3 - Php

> 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.

Solution 4 - Php

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.

Solution 5 - Php

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);
?>

Solution 6 - Php

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']}");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBelgin FishView Question on Stackoverflow
Solution 1 - PhprobjmillsView Answer on Stackoverflow
Solution 2 - PhpYaşar XavanView Answer on Stackoverflow
Solution 3 - PhpPekkaView Answer on Stackoverflow
Solution 4 - PhpMike CaronView Answer on Stackoverflow
Solution 5 - PhpMochammad TaufiqView Answer on Stackoverflow
Solution 6 - Phpdarighteous1View Answer on Stackoverflow