How 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.
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['singlefile']['name']; $_FILE['singlefile']['type']; $_FILE['singlefile']['tmp_name']; $_FILE['singlefile']['error']; $_FILE['singlefile']['error']; $_FILE['myfile']['name']['a']['b'][0]; $_FILE['myfile']['type']['a']['b'][0]; $_FILE['myfile']['tmp_name']['a']['b'][0]; $_FILE['myfile']['error']['a']['b'][0]; $_FILE['myfile']['error']['a']['b'][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['name'], $uploadFiles['type'], $uploadFiles['tmp_name'], $uploadFiles['error'], $uploadFiles['size']); } // 格式化上传文件数组 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] = [ 'name' => $fileName, 'type' => $type[$idx] ?? '', 'tmp_name' => $tmp_name[$idx] ?? '', 'error' => $error[$idx] ?? '', 'size' => $size[$idx] ?? '', ]; } } } else { // 组合单个的内容 $tmpFiles = [ 'name' => $fileName, 'type' => $type ?? '', 'tmp_name' => $tmp_name ?? '', 'error' => $error ?? '', 'size' => $size ?? '', ]; } 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
