search
HomeBackend DevelopmentPHP ProblemHow to format multiple file uploads in PHP

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:慕课网. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.