How to display an image with file_get_contents

Asked

Viewed 863 times

-1

I want to display the image after deleting from the server, also do not know if this is the way to go.

I tried it, unsuccessfully:

 if (file_exists('carro.jpg'))
 {
    $imagem = file_get_contents('carro.jpg');
    //unlink('$imagem')
    echo "<img src='$imagem;'>";
 }
  • what does it mean to display the image? you just have it ready? There’s still a lot to be done.

1 answer

3

With the URI Scheme data protocol

The file_get_contents only returns content binary image, if you want to display an image and delete in the same call you can use the data URI Scheme, thus:

function mimeType($file)
{
    $mimetype = false;

    if (class_exists('finfo')) {//PHP5.4+
        $finfo     = finfo_open(FILEINFO_MIME_TYPE);
        $mimetype  = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {//php5.3 ou inferiror
        $mimetype = mime_content_type($file);
    }

    return $mimetype;
}


if (file_exists('carro.jpg'))
{
    $data = base64_encode(file_get_contents('carro.jpg'));

    $mime = mimeType('carro.jpg');

    unlink('carro.jpg');

    echo '<img src=" data:' , $mime , ';base64,' , $data , '">';
}

With PHP and HTML

If for some reason you can’t use the data URI Scheme, you will have that create more than one request, do the following create a file called photo.php with this content:

<?php
function mimeType($file)
{
    $mimetype = false;

    if (class_exists('finfo')) {//PHP5.4+
        $finfo     = finfo_open(FILEINFO_MIME_TYPE);
        $mimetype  = finfo_file($finfo, $file);
        finfo_close($finfo);
    } else if (function_exists('mime_content_type')) {//php5.3 ou inferiror
        $mimetype = mime_content_type($file);
    }

    return $mimetype;
}

$path = empty($_GET['path']) ? null : $_GET['path'];

if ($path && file_exists($path))
{
    $mime = mimeType($path);

    //Muda content-type para que o arquivo php seja reconhecido como imagem
    header('Content-Type: ' . $mime);

    //Exibe
    echo file_get_contents($path);

    //Deleta
    unlink($path);
} else {
    header('HTTP/1.0 404 Not Found');
}

And in your other file call it:

if (file_exists('carro.jpg'))
{
    echo '<img src="foto.php?path=carro.jpg">';
}
  • Your solution is a good alternative is almost what I need, doubt now is; using base64_encode to display the image I will have problem if the image is too heavy example 8mb 10mb and compatibility all browsers will work?

  • @Rose edited response

Browser other questions tagged

You are not signed in. Login or sign up in order to post.