PHP记住文件字段内容 [英] PHP remember file field contents

查看:93
本文介绍了PHP记住文件字段内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有文本输入和文件输入的表格;文本字段正在验证中.是否有一种方法可以让表单记住用户单击提交"但由于其中一个文本字段未通过验证而需要返回的文件,已经选择了哪些文件?

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?

推荐答案

出于安全原因,您无法预填充"文件上传字段的内容.而且,这意味着每次提交表单时都会重新上传文件,这不是很好.

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:

  • 创建一个名为file_upload的文件上传字段.
  • 在服务器端,无论表单验证的其余部分是否失败,都应处理上载.
  • 如果表单验证失败,但文件已上传,则将隐藏的输入插入名称为file的表单中,其中包含刚上传的文件的名称.
  • 显示文件可见的用户可见指示.如果是图像,请显示其缩略图版本.如果是其他文件,请显示其文件名和/或图标.
  • 如果用户选择在file_upload字段中上传其他文件,请处理上载并将新值存储在file中.
  • 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.

伪代码:

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

重要提示

此机制可以允许任何用户通过包含他们猜测服务器上存在的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.

这篇关于PHP记住文件字段内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆