Home >Backend Development >PHP Problem >How to format multiple file uploads in PHP

How to format multiple file uploads in PHP

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-05-10 17:19:452148browse

This article will introduce you to the method of formatting multiple file uploads in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to format multiple file uploads in PHP

Recommended: "2021 PHP interview questions summary (collection)" "php video tutorial"

File uploading is the most common function in all web applications, and it is very simple to implement this function in PHP. We only need to set the enctype value of the form to multipart/form-data on the front end, and then we can obtain the information in the form through $_FILES The contents of the file control.

At the same time, we can also write the name of the file control as an array with [], so that we can receive multiple uploaded files. For example, the following form is used for testing:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="" enctype="multipart/form-data" method="post">

    myfile1:<input type="file" name="myfile[]"/><br/>
    myfile2:<input type="file" name="myfile[a][]"/><br/>
    myfile3:<input type="file" name="myfile[a][b][]"/><br/>
    myfile4:<input type="file" name="myfile[c][]"/><br/>
    myfile5:<input type="file" name="myfile[]"/><br/>
    myfile6:<input type="file" name="myfile[][]"/><br/>
    <br/>
    newfile1:<input type="file" name="newfile[][]"/><br/>
    newfile2:<input type="file" name="newfile[s]"/><br/>

    singlefile: <input type="file" name="singlefile"/><br/>
        <input type="submit" value="submit"/>
    </form>
</body>
</html>

There are 9 file controls in total, among which myfile and newfile are both array type form names, while singlefile is a separate one. First, let’s take a brief look at the content obtained by $_FILES.

print_r($_FILES);

Array
(
    [myfile] => Array
        (
            [name] => Array
                (
                    [0] => 2591d8b3eee018a0a84f671933ab6c74.png
                    [a] => Array
                        (
                            [0] => 12711584942474_.pic_hd 1.jpg
                            [b] => Array
                                (
                                    [0] => 12721584942474_.pic_hd 1.jpg
                                )

                        )

                    [c] => Array
                        (
                            [0] => 12731584942474_.pic_hd.jpg
                        )

                    [1] => background1.jpg
                    [2] => Array
                        (
                            [0] => adliu_pip_data.xlsx
                        )

                )

            [type] => Array
                (
                    [0] => image/png
                    [a] => Array
                        (
                            [0] => image/jpeg
                            [b] => Array
                                (
                                    [0] => image/jpeg
                                )

                        )

                    [c] => Array
                        (
                            [0] => image/jpeg
                        )

                    [1] => image/jpeg
                    [2] => Array
                        (
                            [0] => application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                        )

                )

            [tmp_name] => Array
                (
                    [0] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phphD88ZY
                    [a] => Array
                        (
                            [0] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpNY8MzY
                            [b] => Array
                                (
                                    [0] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/php3MX5tk
                                )

                        )

                    [c] => Array
                        (
                            [0] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpjgrHMj
                        )

                    [1] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phppXRtnc
                    [2] => Array
                        (
                            [0] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpekSY1M
                        )

                )

            [error] => Array
                (
                    [0] => 0
                    [a] => Array
                        (
                            [0] => 0
                            [b] => Array
                                (
                                    [0] => 0
                                )

                        )

                    [c] => Array
                        (
                            [0] => 0
                        )

                    [1] => 0
                    [2] => Array
                        (
                            [0] => 0
                        )

                )

            [size] => Array
                (
                    [0] => 4973
                    [a] => Array
                        (
                            [0] => 3007
                            [b] => Array
                                (
                                    [0] => 1156
                                )

                        )

                    [c] => Array
                        (
                            [0] => 6068
                        )

                    [1] => 393194
                    [2] => Array
                        (
                            [0] => 36714
                        )

                )

        )

    [newfile] => Array
        (
            [name] => Array
                (
                    [0] => Array
                        (
                            [0] => 数据列表 (2).xlsx
                        )

                    [s] => background1.jpg
                )

            [type] => Array
                (
                    [0] => Array
                        (
                            [0] => application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                        )

                    [s] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => Array
                        (
                            [0] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phplSsRfM
                        )

                    [s] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpuQAvRb
                )

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

                    [s] => 0
                )

            [size] => Array
                (
                    [0] => Array
                        (
                            [0] => 77032
                        )

                    [s] => 393194
                )

        )

    [singlefile] => Array
        (
            [name] => timg (8).jpeg
            [type] => image/jpeg
            [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpxtSQ4J
            [error] => 0
            [size] => 10273
        )

)

Do you see any problem?

$_FILE[&#39;singlefile&#39;][&#39;name&#39;];
$_FILE[&#39;singlefile&#39;][&#39;type&#39;];
$_FILE[&#39;singlefile&#39;][&#39;tmp_name&#39;];
$_FILE[&#39;singlefile&#39;][&#39;error&#39;];
$_FILE[&#39;singlefile&#39;][&#39;error&#39;];

$_FILE[&#39;myfile&#39;][&#39;name&#39;][&#39;a&#39;][&#39;b&#39;][0];
$_FILE[&#39;myfile&#39;][&#39;type&#39;][&#39;a&#39;][&#39;b&#39;][0];
$_FILE[&#39;myfile&#39;][&#39;tmp_name&#39;][&#39;a&#39;][&#39;b&#39;][0];
$_FILE[&#39;myfile&#39;][&#39;error&#39;][&#39;a&#39;][&#39;b&#39;][0];
$_FILE[&#39;myfile&#39;][&#39;error&#39;][&#39;a&#39;][&#39;b&#39;][0];

A single form is an array with singlefile as the key name, which contains the corresponding name, type and other attributes. This is very simple and clear, but the content uploaded in the form of an array is more complicated. There are multiple values ​​under each attribute, and these values ​​​​may also be nested arrays.

For example, if we want to get the uploaded file content of myfile[a][b][], we need to pass \$_FILE['myfile']['name']['a'][' b'][0], $_FILE['myfile']['type']['a']['b'][0] to obtain relevant content.

This is really not very friendly, so here is our topic today. Let’s format this content and make it have a structure similar to singlefile, which is the relevant content of a file. They are all under a key name structure. For example, the contents of myfile[a][b][] are all under $_FILE['myfile'][a][b][0].

$files = [];
// 开始数据格式化
foreach ($_FILES as $uploadKey => $uploadFiles) {
    // 需要将 $_FILES 中的五个字段都拿出来
    $files[$uploadKey] = formatUploadFiles($uploadFiles[&#39;name&#39;], $uploadFiles[&#39;type&#39;], $uploadFiles[&#39;tmp_name&#39;], $uploadFiles[&#39;error&#39;], $uploadFiles[&#39;size&#39;]);
}

// 格式化上传文件数组
function formatUploadFiles($fileNamesArray, $type, $tmp_name, $error, $size)
{
    $tmpFiles = [];
    // 文件名是否是数组,如果不是数组,就是单个文件上传
    if (is_array($fileNamesArray)) {
        // 数组形式上传
        foreach ($fileNamesArray as $idx => $fileName) {
            // 如果还是嵌套的数组,递归遍历接下来的内容
            if (is_array($fileName)) {
                $tmpFiles[$idx] = formatUploadFiles($fileName, $type[$idx] ?? [], $tmp_name[$idx] ?? [], $error[$idx] ?? [], $size[$idx] ?? []);
            } else {
                // 组合多维的格式化内容
                $tmpFiles[$idx] = [
                    &#39;name&#39; => $fileName,
                    &#39;type&#39; => $type[$idx] ?? &#39;&#39;,
                    &#39;tmp_name&#39; => $tmp_name[$idx] ?? &#39;&#39;,
                    &#39;error&#39; => $error[$idx] ?? &#39;&#39;,
                    &#39;size&#39; => $size[$idx] ?? &#39;&#39;,
                ];
            }
        }
    } else {
        // 组合单个的内容
        $tmpFiles = [
            &#39;name&#39; => $fileName,
            &#39;type&#39; => $type ?? &#39;&#39;,
            &#39;tmp_name&#39; => $tmp_name ?? &#39;&#39;,
            &#39;error&#39; => $error ?? &#39;&#39;,
            &#39;size&#39; => $size ?? &#39;&#39;,
        ];
    }

    return $tmpFiles;
}

print_r($files);

The code is still very easy to understand. It traverses the entire $_FILES directory tree through a period of recursion, which is equivalent to a deep traversal. Of course, this will also bring about performance degradation, after all, it requires loop and recursive traversal. Fortunately, in most cases the files we upload are not that many. But on the other hand, if you don't format it in advance, when you want to get all the uploaded content, you still need to perform multi-layer or recursive traversal.

Next let’s take a look at the formatted output:

Array
(
    [myfile] => Array
        (
            [0] => Array
                (
                    [name] => 2591d8b3eee018a0a84f671933ab6c74.png
                    [type] => image/png
                    [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpV7A2yC
                    [error] => 0
                    [size] => 4973
                )

            [a] => Array
                (
                    [0] => Array
                        (
                            [name] => 12711584942474_.pic_hd 1.jpg
                            [type] => image/jpeg
                            [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/php5q2d1Z
                            [error] => 0
                            [size] => 3007
                        )

                    [b] => Array
                        (
                            [0] => Array
                                (
                                    [name] => 12721584942474_.pic_hd 1.jpg
                                    [type] => image/jpeg
                                    [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpdvv8No
                                    [error] => 0
                                    [size] => 1156
                                )

                        )

                )

            [c] => Array
                (
                    [0] => Array
                        (
                            [name] => 12731584942474_.pic_hd.jpg
                            [type] => image/jpeg
                            [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/php9tfGmp
                            [error] => 0
                            [size] => 6068
                        )

                )

            [1] => Array
                (
                    [name] => background1.jpg
                    [type] => image/jpeg
                    [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phplUVpzA
                    [error] => 0
                    [size] => 393194
                )

            [2] => Array
                (
                    [0] => Array
                        (
                            [name] => adliu_pip_data.xlsx
                            [type] => application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                            [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpNRtiaC
                            [error] => 0
                            [size] => 36714
                        )

                )

        )

    [newfile] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [name] => 数据列表 (2).xlsx
                            [type] => application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                            [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpBLG7aG
                            [error] => 0
                            [size] => 77032
                        )

                )

            [s] => Array
                (
                    [name] => background1.jpg
                    [type] => image/jpeg
                    [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpjyqCFY
                    [error] => 0
                    [size] => 393194
                )

        )

    [singlefile] => Array
        (
            [name] =>
            [type] => image/jpeg
            [tmp_name] => /private/var/folders/wj/t2z1cfhs0m9gq48krm8nc0vm0000gn/T/phpuYJXiE
            [error] => 0
            [size] => 10273
        )

)

Is it much clearer and clearer than the original $_FILES above? This time if we need all the contents in myfile[a][b][], we can use the following method to easily obtain it:

re class="brush:php;toolbar:false;" >$files['myfile']['a']['b'][0]['name']; $files['myfile']['a']['b'][0]['type']; $files['myfile']['a']['b'][0]['tmp_name']; $files['myfile']['a']['b'][0]['error']; $files['myfile']['a']['b'][0]['size'];

Of course, this kind of demand is rare in our daily work, and it is also here Just to provide an idea, it is a very good habit to convert the data into the format we need in advance, which can make our subsequent operations very simple.

The above is the detailed content of How to format multiple file uploads in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:imooc.com. If there is any infringement, please contact admin@php.cn delete