Show image using file_get_contents
Asked Answered
E

7

53

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!

Encroach answered 26/11, 2010 at 15:48 Comment(0)
M
37

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.

Milden answered 26/11, 2010 at 15:51 Comment(3)
alright, and Header("Content-Type: image/jpg"); should be sufficient?Encroach
@Belgin if it's a JPG image, yes.Milden
doesn't it need to image/jpeg ?Boilermaker
P
88

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.

Psychosexual answered 26/11, 2010 at 15:52 Comment(2)
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']);Laris
For those who are receiving the error "the image cannot be displayed" or just an "empty screen". Just start your document with <?php followed by the code to display the image, without any html code before.Perusse
A
64
$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 . '">';
Anette answered 6/2, 2014 at 10:49 Comment(1)
I used this to make google staticmaps work in Safari and Chrome, works perfectly.Endamoeba
M
37

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.

Milden answered 26/11, 2010 at 15:51 Comment(3)
alright, and Header("Content-Type: image/jpg"); should be sufficient?Encroach
@Belgin if it's a JPG image, yes.Milden
doesn't it need to image/jpeg ?Boilermaker
I
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.

Irruptive answered 26/11, 2010 at 15:52 Comment(0)
T
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);
?>
Thatcher answered 11/10, 2012 at 4:0 Comment(0)
R
0

we can identify Mime type using File Signature. refer this for know more about what is file signatures

function getBytesFromHexString($hexdata)
{
    for($count = 0; $count < strlen($hexdata); $count+=2)
        $bytes[] = chr(hexdec(substr($hexdata, $count, 2)));
    
    return implode($bytes);
}

function getImageMimeType($imagedata)
{
    $imagemimetypes = [
        "jpeg" => "FFD8", 
        "png" => "89504E470D0A1A0A", 
        "gif" => "474946",
        "bmp" => "424D", 
        "tiff" => "4949",
        "tiff" => "4D4D"
    ];
 
    foreach ($imagemimetypes as $mime => $hexbytes)
    {
        $bytes = getBytesFromHexString($hexbytes);
        if (substr($imagedata, 0, strlen($bytes)) == $bytes)
            return $mime;
    }
  
    return NULL;
}

$uri = "your img url";

if($img = file_get_contents($uri)) {
    echo $mimeType = $this->getImageMimeType($img);
}

for more details see here

Ridgway answered 9/2, 2023 at 12:19 Comment(0)
F
-1

prevent ddos

function view_file($f){
        if(is_file($f)){
            $ext=strtolower(pathinfo($f,PATHINFO_EXTENSION));
            $gambar=array('jpg','jpeg','jpe','jif','jfif','jfi','png','gif','webp','tiff','tif','bmp','dib','heif','heic','jp2','j2k','jpf','jpx','jpm','mj2','svg','svgz');
            $video=array('webm','mpg','mp2','mpeg','mpe','mpv','ogg','mp4','m4p','m4v','avi','avi','mov','qt','flv','swf');
            $audio=array('wav','aif','mp3','mid');
            $t=24;
            $time=time();
            $interval=3600*$t;
            if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){
                $modified_time=@$_SERVER['HTTP_IF_MODIFIED_SINCE'];
                if(strtotime($modified_time)+$interval>time()){
                    header("HTTP/1.1 304");
                }
            }
            header('Cache-Control: public');
            header('Last-Modified: '.gmdate('r',$time));
            header('Expires: '.gmdate('r',($time+$interval)));
            header('Cache-Control: max-age='.$interval);
            $c=' style="margin:0;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);">';
            $_64='src="data:'.$ext.';base64,'.base64_encode(file_get_contents($f)).'"';
            if(in_array($ext,$gambar)){
                $s='<div'.$c.'<img '.$_64.'></div>';
            }elseif(in_array($ext,$video)){
                $s='<video style="position:fixed;right:0;bottom:0;min-width:90%;min-height:90%;width:auto;height:auto;z-index:-100;" controls autoplay loop playsinline>'.
                    '<source '.$_64.' type="video/'.$ext.'"></video>';
            }elseif(in_array($ext,$audio)){
                $s='<div'.$c.'<h4>'.$f.'</h4><audio controls autoplay loop><source '.$_64.' type="audio/'.$ext.'"></audio></div>';
            }else{
                setlocale(LC_ALL,'en_US.UTF-8');
                $s='<pre style="line-height:unset;background-color:#fff">'.mb_convert_encoding(highlight_string(file_get_contents($f),1),'ISO-8859-2','UTF-8').'</pre>';
            }
            return(die($s));
        }else{return(false);}
    }
Fortify answered 22/7, 2023 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.