如何防止上载脚本在页面重新加载上移动文件?

时间:2014-10-19 10:31:11

标签: php

表格:

<div id="maindiv">

            <div id="formdiv">
                <h2>Multiple Image Upload Form</h2>
                <form enctype="multipart/form-data" action="" method="post">
                    First Field is Compulsory. Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.
                    <hr/>
                    <div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>

                    <input type="button" id="add_more" class="upload" value="Add More Files"/>
                    <input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
                </form>
                <br/>
                <br/>
                <!-------Including PHP Script here------>
                <?php include "upload.php"; ?>
            </div>

        </div>

剧本:

<?php
if (isset($_POST['submit'])) {
    $j = 0; //Variable for indexing uploaded image

    $target_path = "uploads/"; //Declaring Path for uploaded images
    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

        $validextensions = array("jpeg", "jpg", "png");  //Extensions which are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
        $file_extension = end($ext); //store extensions in the variable

        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
        $j = $j + 1;//increment the number of uploaded images according to the files in array

      if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
                && in_array($file_extension, $validextensions)) {
            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
            } else {//if file was not moved.
                echo $j. ').<span id="error">please try again!.</span><br/><br/>';
            }
        } else {//if file size and file type was incorrect.
            echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
        }
    }
}
?>

此脚本还使用javascript进行多个图片上传。

在网络浏览器中点击 &#34;页面重新加载&#34; 时, 之后第一次上传已经完成, 然后 脚本会为同一个文件分配 新的ID代码 并移动图像将 第二次 文件存入&#34;上传&#34; 文件夹。

如何阻止脚本将图像文件(为名称分配新的ID代码) 第二次移动到&#34;上传&#34; 文件夹?

非常感谢任何建议。

修改

所以,我选择了#34;重定向&#34;在提交完成后,表单获取 清除 的同一页面。

看起来,这是实现它的方法。

1 个答案:

答案 0 :(得分:0)

在上传之前(您显示上传表格),您可以创建一个密钥(随机)并将其存储在您的服务器上。 (临时文件夹)(使用序列号更安全) 您可以在上传表单中将其包含为“隐藏”值。 正在处理上传的脚本应首先查找此密钥,如果存在,您可以将其删除并继续重命名/上传/您想要执行的任何操作。 如果密钥消失了,您可以确定它是一个重复的请求,只需忽略它。

不要忘记每次都清理你的临时文件夹(假设删除超过一小时左右的每个键)