问题上传多个同名文件

时间:2014-12-27 09:49:33

标签: php multifile-uploader

我在PHP中有一个多文件上传表单。我的问题是,当上传两个同名图像时,第二个图像被前一个图像替换。我能做什么?这是我的代码:

HTML

<form action="" enctype="multipart/form-data" method="post">

    <div>
        <label for='upload'>Add Attachments:</label>
        <input id='upload' name="upload[]" onChange="read_url(this)" type="file" multiple="multiple" id="imgInp" />
    </div>

    <p><input type="submit" name="submit" value="Submit"></p>

</form>

PHP代码

if(isset($_POST['submit'])){
    if(count($_FILES['upload']['name']) > 0){
        //Loop through each file
        for($i=0; $i<count($_FILES['upload']['name']); $i++) {
          //Get the temp file path
            $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

            //Make sure we have a filepath
            if($tmpFilePath != ""){

                //save the filename
                $shortname = $_FILES['upload']['name'][$i];

                //save the url and the file
                $filePath = "store/".$_FILES['upload']['name'][$i];

                //Upload the file into the temp dir
                if(move_uploaded_file($tmpFilePath, $filePath)) {

                    $files[] = $shortname;

                    $name = 'Admin';

                    $qry="INSERT INTO test(Name,Image) VALUES('$name','$filePath')";

                    mysqli_query($link,$qry) or die(mysqli_error($link));




                    //use $shortname for the filename
                    //use $filePath for the relative url to the file

                }   
            }
            echo '<p style="color:#000;">SUCCESS!!</p>';

        }
    }

建议我....

1 个答案:

答案 0 :(得分:3)

您可以重命名每个文件的文件名。最简单的方法就是用它来连接它,例如

$filename = $_FILES['myfilename']['name'];
$filename = time().$filename;