Displaying an image with file_get_contents

-1

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

I tried this, without success:

 if (file_exists('carro.jpg'))
 {
    $imagem = file_get_contents('carro.jpg');
    //unlink('$imagem')
    echo "<img src='$imagem;'>";
 }
    
asked by anonymous 07.09.2016 / 05:53

1 answer

3

With the protocol data URI scheme

file_get_contents only returns binary content > of the image, if you want to display an image and delete it on the same call you can use the data URI scheme a>, like this:

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 not use the data URI scheme , you will have to 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 like this:

if (file_exists('carro.jpg'))
{
    echo '<img src="foto.php?path=carro.jpg">';
}
    
07.09.2016 / 06:06