search
HomeBackend DevelopmentPHP TutorialPHP multiple file upload operation_PHP tutorial

PHP multi-file upload operation

In fact, multiple file uploads and single file uploads are similar. The principles are the same, but there are some tricks in the code.
The first is the index.html upload form, but the file in the previous file upload form is changed to file[]
Copy code
upload files
Upload file:
Upload file:
Upload file:
Copy code
Use $_FILES in upload.php to print it
print_r($_FILES);
?>
Get the following multi-dimensional array
Copy code
Array
(
[file] => Array
(
[name] => Array
          (
                  [0] => Photo 1.jpg
                  [1] => Photo 2.jpg
                                                                                                                                                                                                                                                               
        )
[type] => Array
          (
                                                                                                                                                                   
                                                                                                                                                                                               
                                                                                                                                                                                                           
        )
[tmp_name] => Array
          (
                                                                                                                        [0] => [1] => [2] =>
        )
[error] => Array
          (
                  [0] => 0
                    [1] => 0
                  [2] => 0
        )
[size] => Array
          (
                  [0] => 0
                  [1] => 0
                  [2] => 0
        )
)
)
Copy code
According to the principle of single file upload, first think about what we need to get?
Obviously we need to get an array of file information. The array contains name, type, tmp_name, error, size. What we get at this time is a multi-dimensional array. Although the corresponding key values ​​exist, it is multi-dimensional. ,
We only need to split it, such as the three files above, we only need to split it into the corresponding three file information arrays.
Structure of split array
Copy code
Array
(
[0] => Array
(
             [name] => Photo 1.jpg
[type] => image/jpeg
>
                                                                                                                                                                                                                 ​ >
)
[1] => Array
(
[name] = & gt; Photo 2.jpg
[type] => image/jpeg
>
                                                                                                                                                                                                                 ​ >
)
[2] => Array
(
[name] => Photo 3.jpg
[type] => image/jpeg
>
                                                                                                                                                                                                                 ​ >
)
)
Copy code
The following is the code for splitting and reorganizing the array
Copy code
//print_r($_FILES['file']);
$arr=$_FILES['file'];
$files=array();
for($i=0;$i
$files[$i]['name']=$arr['name'][$i];
$files[$i]['type']=$arr['type'][$i];
$files[$i]['tmp_name']=$arr['tmp_name'][$i];
$files[$i]['error']=$arr['error'][$i];
$files[$i]['size']=$arr['size'][$i];
}
print_r($files);
?>
Copy code
The rest is simple. Just repeat the steps of uploading a single file and iterate through the array.
The code is as follows:
Copy code
//print_r($_FILES['file']);
$arr=$_FILES['file'];
$files=array();
for($i=0;$i $files[$i]['name']=$arr['name'][$i];
$files[$i]['type']=$arr['type'][$i];
$files[$i]['tmp_name']=$arr['tmp_name'][$i];
$files[$i]['error']=$arr['error'][$i];
$files[$i]['size']=$arr['size'][$i];
}
for($i=0;$i //Get uploaded file information
$fileName=$files[$i]['name'];
$fileType=$files[$i]['type'];
$fileError=$files[$i]['type'];
$fileSize=$files[$i]['size'];
$tempName=$files[$i]['tmp_name'];//Temporary file name
//Define upload file type
$typeList = array("image/jpeg","image/jpg","image/png","image/gif"); //Define allowed types
if($fileError>0){
//Judge the error number of uploaded files
switch ($fileError) {
case 1:
$ message = "uploaded files exceeded the value restricted by upload_max_filesize options in php.ini.";
break;
case 2:
                                                                                                                                                                                                $message="The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form.";
break;
case 3:
                        $message="Only part of the file has been uploaded.";
break;
case 4:
                            $message="No files uploaded.";
break;
case 6:
$ message = "Can't find the temporary folder.";
break;
case 7:
                        $message="File writing failed";
break;
case 8:
                                $message="File upload interrupted due to PHP extension";
break;
      }
exit("File upload failed: ".$message);
}
if(!is_uploaded_file($tempName)){
//Determine whether it is a file uploaded by POST
exit("It was not uploaded via HTTP POST");
}else{
if(!in_array($fileType, $typeList)){
exit("The uploaded file is not of the specified type");
}else{
if(!getimagesize($tempName)){
                                                                                                                                                            // Prevent users from uploading malicious files, such as changing the virus file extension to image format
exit("The uploaded file is not a picture");
      }
}
if($fileSize>1000000){
                                                                                                                                                                                                              ’ ’       ’ to ’     ’                     out‐‐ together ‐ out‐download of a specific form to be uploaded
                    exit("Uploaded file exceeds limit size");
      }else{
// Avoid the Chinese name garbled in the Chinese name
                                                      $fileName=iconv("UTF-8", "GBK", $fileName);//Convert the character encoding captured by iconv from utf-8 to gbk output
$ filename = strlaplace (".", Time (). ".", $ Filename); // Add the time stamp after the picture name, avoid the re -name file coverage
                                                                                                                                                                                                                                                                                   
                        echo "File uploaded successfully!";
        }else{
                                                                                                                                                                having having  -                                           echo "Failed to upload file";
        }
      }
}
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/855346.htmlTechArticlePHP multi-file upload operation is actually similar to multi-file upload and single-file upload. The principles are the same, but in the code Did a little trick on it. The first is the index.html upload form, just...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)