PHP上传多个文件在错误检查时停止


php uploading multiple files halts on error check

我试图上传多个文件,通过改变我曾经用来上传单个文件的脚本。

我所做的唯一更改是向表单添加更多的文件输入字段。但是当我将表单提交给脚本时,它停在我检查错误的地方。如何处理多个文件?

$form  = '<form action="imgProcess.php" method="post" enctype="multipart/form-data">';
$form .= '<div><input type="file" name="file[]"></div>';
$form .= '<div><input type="file" name="file[]"></div>';
$form .= '<div><input type="file" name="file[]"></div>';
$form .= '<div><input type="file" name="file[]"></div>';
$form .= '<div><input type="file" name="file[]"></div>';
$form .= '<input type="hidden" name="handle" value="testHandle" />';
$form .= '<input type="submit">';
$form .= '</form>';

imgProcess.php

if($_FILES && isset($_POST['handle'])) {
    $numFiles = count($_FILES['file']['tmp_name']);
    echo $numFiles;
    $handle = $_POST['handle'];
    echo $handle;
    // Halt on errors
    if($_FILES['file']['error'] == 0) {

    } else {
        echo 'There were errors<br>';
        print_r( $_FILES['file']['error'] );
    }
} else {
    echo 'Error 1';
}
//
There were errors
Array ( [0] => 0 [1] => 0 [2] => 4 [3] => 4 [4] => 4 )

你有5个元素的文件

而你打印的错误信息中的状态码显示你只上传了两个文件。

Array ( [0] => 0 [1] => 0 [2] => 4 [3] => 4 [4] => 4 )
                                 ^        ^        ^

其余的保留为空,您提交了表单。参考 this 了解细节

这就是给出错误的原因。您可能必须以不同的方式处理它,以便它只考虑您上传的文件。

您可以在输入字段中添加属性"multiple",而不是添加许多输入字段。在PHP官方网站你可以找到如何上传多个文件的例子

从所有文件中如果你想上传那些没有任何错误的文件那么使用try和catch如果你想抛出错误如果其中任何一个有错误那么改变你的条件来检查错误,像这样

$fileUploadError = array_filter($_FILES['file']['error']);
if(count($fileUploadError) > 0 ) { 
     echo "error";    
} else {
     echo "no error";    
}

希望这对你有帮助

请尝试一下

    $error=$_FILES['file']['error'];
for($i=0;$i<$numFiles;$i++)
{
     if($error[$i] == 0) {
        //your code
    } 
}