1

I have an form that I submit which has among other inputs, an image input like so:

<label id="labelEnviarImagem" for='enviarImagem'>Choose a file &#187;</label><br>
<input required type="file" name="productFile" id="enviarImagem">

My problem is the following:

Sometimes, other inputs from the form won't be valid, and the PHP will return the user to the form page while saving the previous values on the $_SESSION so the user has the form pre-filled and will be able to fix their mistakes without having to re-type everything. How can I do the same for the image?

I've tried to save the image on the session and then pass that as the value to the input, but obviously it didn't work.

$_SESSION["dadosProduct"]["img"] = $_FILES['productFile']['tmp_name'];

<input required type="file" name="productFile" value="<?php echo isset($_SESSION['dadosProduct']) ? $_SESSION['dadosProduct']['name'] : ""; ?>" id="enviarImagem">

My question is: I can save the information when the input type is text/number by using the $_SESSION easily, how can I do the same when the input type="file"?

Antonio Neto
  • 176
  • 10
  • Possible duplicate of [PHP Keep entered values after validation error](https://stackoverflow.com/questions/33276966/php-keep-entered-values-after-validation-error) – aa-Ahmed-aa Mar 29 '18 at 13:06
  • Not a duplicate, my code is relative to the input of the type file. As you can see I've already tried to solve the problem using the path that's explained on that question. – Antonio Neto Mar 29 '18 at 13:09
  • @AntonioNeto You can do 1 think before checking the server side validation upload the file to server and store the value in session. and display those session image on form if validation fail. Its a simple solution. – Narayan Mar 29 '18 at 13:17

1 Answers1

1

I've tried to save the image on the session

There are two problems with your attempt to do that.

Garbage collection

You are storing the filename in the session, but as soon as the script finishes the file will be deleted, so you are storing the name of a file that no longer exists.

You need to store the file somewhere more permanent (and implement your own garbage collection to clean it up after some time has passed).

File inputs

A file input is designed to upload files from the computer hosting the browser.

Setting the value of it to the path of a file on the server makes no sense (and you can't set the value of a file input anyway).

You need to provide some other kind of UI.

This might just be a plain paragraph that states a file, with the name whatever.ext has been stored in the user's session.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • So, in theory. I should upload the file to the server to a temporary place, and have the information that a temporary file has been uploaded saved on the session, so when the user tries to send the form again i'll be able to use his previous file? – Antonio Neto Mar 29 '18 at 13:25