【问题标题】:Multiple file upload in PHP always drops first filePHP中的多个文件上传总是丢弃第一个文件
【发布时间】:2021-04-15 16:09:35
【问题描述】:

我正在尝试像这样的 PHP 多文件上传的不同示例

<html>
<body>
<form action="upload.php" enctype="multipart/form-data" method="post">

    <div>
        <label for='upload'>Add files</label>
        <input id='upload' name="upload[]" type="file" multiple="multiple" />
    </div>

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

</form>
</body>
</html>
<?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 = $_FILES['upload']['name'][$i];

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

                    $files[] = $shortname;
                    //insert into db 
                    //use $shortname for the filename
                    //use $filePath for the relative url to the file

                }
              }
        }
    }

    //show success message
    echo "<h1>Uploaded:</h1>";    
    if(is_array($files)){
        echo "<ul>";
        foreach($files as $file){
            echo "<li>$file</li>";
        }
        echo "</ul>";
    }
}
?>

问题是它检测到 3 个文件但只上传了 2 个文件,而第一个文件总是丢失。 我没有收到任何错误消息,所以无法理解发生了什么。我尝试了其他一些多上传代码示例,但情况相同。

【问题讨论】:

    标签: php forms file upload


    【解决方案1】:

    我读了这条评论:

    https://www.php.net/manual/en/reserved.variables.files.php#89674

    而且文件不是编号file0file1file2等,而是file1file2file3。可能是数字索引也不是012 等,而是123 等。所以在你的情况下,你可以通过这样做来纠正:

    $tmpFilePath = $_FILES['upload']['tmp_name'][$i+1];
    $shortname = $_FILES['upload']['name'][$i+1];
    $filePath = $_FILES['upload']['name'][$i+1];
    

    我没有测试过这个,我也不确定这个,但是你很容易检查它,只需做一个:

    var_dump($_FILES);
    

    【讨论】:

      猜你喜欢
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      相关资源
      最近更新 更多