Save Image Coming from Upload in a PHP variable

Asked

Viewed 376 times

0

How to capture an image that comes from an HTML file type input, in a PHP variable? For example with a text input works this way:

$vnome = ($_POST["f_nome"]);
echo $vnome;

<input type="text" name="f_nome">

How to do the same with an image? It is possible to save image in a PHP variable?

1 answer

1


The server along with PHP before running your script has already done the "parse" of PAYLOAD and saved the image in the folder ./tmp configured by php.ini in upload_tmp_dir, then you can upload normally and use file_get_contents, a basic example would be:

<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="arquivo" multiple>
<button type="submit">Upload</button>
</form>

And php would be:

<?php

if (empty($_FILES['arquivo']['tmp_name'])) {
     die('Erro no upload');
}

//Pega os dados do upload
$dados_da_imagem = file_get_contents($_FILES['arquivo']['tmp_name']);

If you want to display on screen you have to use data URI Scheme, something like:

$dados_da_imagem = file_get_contents($_FILES['arquivo']['tmp_name']);

echo '<img src="data:image/gif;base64,', base64_encode($dados_da_imagem),'">';

Now if your intention is to display an image preview before completing the upload, I recommend doing so on front-end, before even sending the POST, example of Javascript tools:

  • This way it is possible to call the "$dados_do_upload" to show the image?

  • @Henriquebretone yes, it is possible, you did not see the example echo '<img src="data:image/gif;base64,', base64_encode($dados_da_imagem),'">';?

  • 1

    @Henriquebretone Now if your intention is to display an image preview before completing the upload (type user wants to check if it is the right photo), I recommend to do it on the front end, even before sending the POST, example of Javascript tools: http://www.dropzonejs.com/ or http://opoloo.github.io/jquery_upload_preview/

  • Not the intention was not to make a thumbnail preview, the idea was to take the image in PHP and play it in an HTML template to generate a PDF that appears-if the image, I am doing this with text quietly the problem is the need to show the image that the user uploaded in the PDF file.

Browser other questions tagged

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