search
HomeBackend DevelopmentPHP TutorialPHP encapsulated single file upload class

PHP encapsulated single file upload class

May 31, 2018 pm 02:35 PM
phpuploaddocument

This article mainly introduces the single file (image) upload class encapsulated by PHP, and analyzes the related processing skills of PHP image file upload operation in the form of a complete example. Friends in need can refer to it.

The details are as follows :

<?php
//封装php中的单文件(图片)上传类
/*
//参数1:$file 文件数组 5个属性值 name,type,size,tmp,error
//参数2:文件保存的路径$path
//参数3:文件上传允许的类型 $allow数组  $allow=array(&#39;image/jpeg&#39;,&#39;image/jpg&#39;,&#39;image/png&#39;,&#39;image/gif&#39;)
//参数4: 允许文件上传的最大大小 $size
//返回值: return $imageName文件的名字
*/
header(&#39;content-type:text/html;charset=utf-8&#39;);
class Upload{
   //定义一个属性,专门保存错误信息
    public static $error;
   //文件转移的方法
  public function uploadFile($file,$size,$path){
    if(!is_dir($path)){
     $this->mkPath($path);
    }
    $allow=array(&#39;image/jpeg&#39;,&#39;image/jpg&#39;,&#39;image/png&#39;,&#39;image/gif&#39;);
   //首先判断文件是否已上传到临时目录
    if(!is_array($file)){
     Upload::$error=&#39;不是一个有效的文件&#39;;
     return false;
    }
   //判断文件是否上传到临时目录成功
   switch($file[&#39;error&#39;]){
    case 1:
      Upload::$error=&#39;上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。&#39;;
      return false;
    case 2:
      Upload::$error=&#39;上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。&#39;;
      return false;
    case 3:
      Upload::$error=&#39;文件只有部分被上传&#39;;
      return false;
    case 4:
      Upload::$error=&#39;没有文件被上传&#39;;
       return false;
    case 6:
      Upload::$error=&#39;找不到临时文件夹&#39;;
      return false;
    case 7:
       Upload::$error=&#39;文件写入失败&#39;;
       return false;
   }
   //判断文件类型是否是图片
    if(!in_array($file[&#39;type&#39;],$allow)){
     Upload::$error=&#39;不是要求的文件类型&#39;;
     return false;
    }
   //判断文件的大小是否在允许的范围内
    if($file[&#39;size&#39;]>$size){
     Upload::$error=&#39;超出允许最大文件大小&#39;;
     return false;
    }
    //文件转移
    if(move_uploaded_file($file[&#39;tmp_name&#39;],$path.&#39;/&#39;.$this->getName($file))){
     return $file[&#39;name&#39;];
    }else{
     return Upload::$error;
    }
  }
  //创建目录的方法
    private function mkPath($path){
    mkdir($path);
  }
  //文件重命名
    private function getName($file){
     return time().$file[&#39;name&#39;];
    }
}

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

Detailed explanation of the implementation steps of in_array implicit conversion in PHP

PHP detailed explanation of the heap sort algorithm

phpWhat are the methods to read local json files

The above is the detailed content of PHP encapsulated single file upload class. For more information, please follow other related articles on the PHP Chinese website!

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.