Antonio Neto
Antonio Neto

Reputation: 176

Save image on input after POST validation fails

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"?

Upvotes: 1

Views: 830

Answers (1)

Quentin
Quentin

Reputation: 943645

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.

Upvotes: 1

Related Questions