PHP使用不同的密钥上传多个文件

时间:2019-08-16 21:02:31

标签: php

是否可以使用具有相同名称和不同键的文件输入在PHP中上传文件?

这样我可以循环在我的PHP代码中发布的字段吗?

<input type="file" name="document_upload[one]" />
<input type="file" name="document_upload[two]" />

foreach($_FILES["instructor_document_upload"] as $doc_upload => $val) {
    if(!empty($_FILES[ $val ]) && !$_FILES[ $val ]["error"]) {

    }
}

2 个答案:

答案 0 :(得分:2)

是的,您可以做到。请记住,$_FILES的外观如下:

Array
(
    [document_upload] => Array
        (
            [name] => Array
                (
                    [one] => file1
                    [two] => file2
                )

            [type] => Array
                (
                    [one] => type1
                    [two] => type2
                )

            [tmp_name] => Array
                (
                    [one] => temp1
                    [two] => temp2
                )

            [error] => Array
                (
                    [one] => 0
                    [two] => 0
                )

            [size] => Array
                (
                    [one] => size1
                    [two] => size2
                )

        )

)

因此,要处理它们,您必须执行以下操作:

foreach ($_FILES['document_upload']['name'] as $fieldname => $filename) {
    echo "File {$filename}; Size: {$_FILES['document_upload']['size'][$fieldname]}\n";
}

答案 1 :(得分:0)

您可以使用此代码。
HTML(请看空的方括号):

<input type="file" name="document_upload[]" />
<input type="file" name="document_upload[]" />

通过这种方式,PHP将document_upload输入视为数组。
PHP代码:

foreach($_FILES["document_upload"] as $doc_upload) {
    // $doc_upload is one of the file you uploaded
}