Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

PHP remember file field contents

I have a form with text inputs and file inputs; the text fields are being validated. Is there a way to have the form remember which files the user has already selected if they hit submit but need to go back because one of the text fields didn't validate?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't "pre-fill" the contents of a file upload field for security reasons. Also, that would mean the file would get re-uploaded every time the form is submitted, which would not be good.

Instead, do this:

  • Create a file upload field with name file_upload.
  • On the server-side, process the upload in any case, even if the rest of the form validation fails.
  • If the form validation failed, but the file was uploaded, insert a hidden input into the form with name file containing the name of the just uploaded file.
  • Display a user-visible indication that the file is okay. If it's an image, display a thumbnail version of it. If it's any other file, display its filename and/or icon.
  • If the user chooses to upload a different file in the file_upload field, process the upload and store the new value in file.

Pseudocode:

<?php
    $file = null;
    if (!empty($_POST['file'])) {
        $file = $_POST['file'];
    }
    if (!empty($_FILES['file_upload'])) {

        // process upload, save file somewhere

        $file = $nameOfSavedFile;
    }

    // validate form
?>


<input type="file" name="file_upload" />
<input type="hidden" name="file" value="<?php echo $file; ?>" />
<?php
    if (!empty($file)) {
        echo "File: $file";
    }
 ?>

Important note

This mechanism can allow any user to claim other user's files as their own, by including a file name that they guessed exists on your server. You will want to ensure that uploaded files are clearly associated with a specific user to avoid this issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...