1

I have an

<input type="text" name="name">
<input type="file" name="photo">

After submit it form, I found some errors, so, I do:

<input type="text" name="name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<input type="file" name="photo" value="WHAT HERE?!">

As you can see, I don't know what I need to write on the value attr to refill the selected file form the user. Can I do that?

Thanks!

0

2 Answers 2

5

Unfortunately, this cannot be done because it presents too many security risks. When a file is uploaded, the browser is not given the actual file path but rather creates a temporary file (with a path value of C:\fakepath) that it can send to the server on processing. So there is no value you can pass through the POST that you can put back into an input to choose a file.

An alternative would be to use AJAX for form validation, that way the user never leaves the page until the form is ready to submit.

Sign up to request clarification or add additional context in comments.

Comments

1

Can I do that?

No, you cant. For security reasons, the value attribute is ignored for input elements of type="file".

Possible workarounds:

  • Keep a reference to the submitted file (that is stored on disk) in a hidden input. Show a message to the user to inform that the file not need to be entered again, because you already have it from previous failed submits.
  • Submit your form via AJAX.
  • Validate as much as possible on the client side with javascript to avoid reloads. This will assume javascript is enabled.

1 Comment

On the first workaround, when you say "keep a reference to the submitted file (that is stored on disk)", do you refer to the temporary file stored on the server?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.