search
HomeBackend DevelopmentPHP TutorialHow to implement multiple file uploads in PHP

The example in this article describes how to implement multiple file uploads in PHP. Share it with everyone for your reference. The specific implementation method is as follows:

  1. define('ROOT','D:/Program Files/www/test/');
  2. class Files_Tool{
  3. protected static $allowExt=array('.jpg','.jpeg ','.png','.gif','.bmp','.svg','.chm','.pdf','.zip','.rar','.tar','.gz ','.bzip2','.ppt','.doc');
  4. public static $wrong=array();
  5. public static $path=array();
  6. protected static $error=array(
  7. 0=> ;'File upload failed, no error occurred, file upload was successful',
  8. 1=>'File upload failed, the uploaded file exceeded the value limited by the upload_max_filesize option in php.ini',
  9. 2=>'File upload failed ,The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form',
  10. 3=>'File upload failed, only part of the file was uploaded',
  11. 4=>'File upload failed, no file was uploaded',
  12. 5=>'File upload failed, suffix not allowed',
  13. 6=>'File upload failed, temporary folder not found. Introduced in PHP 4.3.10 and PHP 5.0.3',
  14. 7=> 'File upload failed, file writing failed. Introduced in PHP 5.1.0',
  15. 8=>'File upload failed, the name of the form field was not received',
  16. 9=>'File upload failed,,error unknown'
  17. );
  18. public static function upload($name){
  19. //Check whether the NAME of the form field is received
  20. if(!isset($_FILES[$name])){
  21. self::$wrong[]=8;
  22. return false;
  23. }
  24. //3D array is simplified into 2D array
  25. $files=array_shift($_FILES);
  26. //Get the suffix
  27. $files=self::get_Ext($files);
  28. //Process files Number of times
  29. $n=count($files['name']);
  30. for($i=0;$i //Check whether the current file has an error message, if so, skip the current one file, process the next file
  31. if($files['error'][$i]!=0){
  32. self::$wrong[$i+1]=$files['error'][$i];
  33. continue;
  34. }
  35. //Check the suffix of the current file, whether it is allowed, if not, skip the current file
  36. if(!in_array($files['name'][$i],self::$allowExt)) {
  37. self::$wrong[$i+1]=5;
  38. continue;
  39. }
  40. //Path
  41. $dir=self::time_Dir();
  42. //File name
  43. $name=self::rand_Name( );
  44. //Suffix
  45. $ext=$files['name'][$i];
  46. //File location
  47. $path=$dir.$name.$ext;
  48. //Move temporary files, if failed, Skip the current file
  49. if(!move_uploaded_file($files['tmp_name'][$i],$path)){
  50. self::$wrong[$i]=9;
  51. continue;
  52. }
  53. //Save Path
  54. self::$path[$i+1]=strtr($path,array(ROOT=>''));
  55. }
  56. return self::$path;
  57. }
  58. //Method to get suffix
  59. protected static function get_Ext($arr){
  60. if(!is_array($arr) || !isset($arr['name'])){return false;}
  61. foreach($arr['name'] as $k =>$v){
  62. $arr['name'][$k]=strtolower(strrchr($v,'.'));
  63. }
  64. return $arr;
  65. }
  66. //Generate path with date
  67. protected static function time_Dir(){
  68. $dir=ROOT.'Data/images/'.date('Y/m/d/',time());
  69. if(!is_dir($dir)){
  70. mkdir( $dir,0777,true);
  71. }
  72. return $dir;
  73. }
  74. //Generate a random file name
  75. protected static function rand_Name(){
  76. $str=str_shuffle('1234567890qwertyuiopasdfghjklzxcvbnm');
  77. $str=substr($ str,0,6);
  78. return $str;
  79. }
  80. //Error interface
  81. public static function errors(){
  82. foreach(self::$wrong as $k=>$v){
  83. self::$ wrong[$k]='th'.$k.'th'.self::$error[$k];
  84. }
  85. return self::$wrong;
  86. }
  87. }
Copy code

I hope this article will be helpful to everyone’s PHP programming design.

File upload, PHP


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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools