Home Backend Development PHP Tutorial Completely encapsulated php upload file class

Completely encapsulated php upload file class

Jul 25, 2016 am 08:43 AM

  1. class FileUpload {
  2. private $filepath; //Specify the path to save the uploaded file
  3. private $allowtype=array('gif', 'jpg', 'png', 'jpeg'); //Allow uploading files Type
  4. private $maxsize=1000000; //The maximum length of uploaded files is 1M
  5. private $israndname=true; //Whether to rename randomly, false is not random, use the original file name
  6. private $originName; //Source file name
  7. private $tmpFileName; //Temporary file name
  8. private $fileType; //File type
  9. private $fileSize; //File size
  10. private $newFileName; //New file name
  11. private $errorNum=0; //Error number
  12. private $errorMess=""; //Used to provide error reports
  13. //Used to initialize uploaded files
  14. //1. Specify the upload path, 2. Allowed type, 3. Limit size, 4. Whether to use Random file name
  15. //Allows users to pass parameters by position, and provide values ​​for subsequent parameters without also providing values ​​for the first few parameters
  16. function __construct($options=array()){
  17. foreach($options as $key=> ;$val){
  18. $key=strtolower($key);
  19. //Check whether the subscript of the array in the user parameter is the same as the member attribute name
  20. if(!in_array($key,get_class_vars(get_class($this))) ){
  21. continue;
  22. }
  23. $this->setOption($key, $val);
  24. }
  25. }
  26. private function getError(){
  27. $str="Upload file Error when {$this->originName}: ";
  28. switch($this->errorNum){
  29. case 4: $str .= "No file was uploaded"; break;
  30. case 3: $str .= "The file was only partially uploaded"; break;
  31. case 2: $str .= "The uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form"; break;
  32. case 1: $str .= "The uploaded file Exceeded the value of the upload_max_filesize option in php.ini"; break;
  33. case -1: $str .= "Unallowed type"; break;
  34. case -2: $str .= "The file is too large and cannot be uploaded Exceeding {$this->maxSize} bytes"; break;
  35. case -3: $str .= "Upload failed"; break;
  36. case -4: $str .= "Failed to create a directory to store uploaded files, please Re-specify the upload directory"; break;
  37. case -5: $str .= "The path to the uploaded file must be specified"; break;
  38. default: $str .= "Unknown error";
  39. }
  40. return $str.'< ;br>';
  41. }
  42. //Used to check the file upload path
  43. private function checkFilePath(){
  44. if(empty($this->filepath)) {
  45. $this->setOption('errorNum', - 5);
  46. return false;
  47. }
  48. if(!file_exists($this->filepath) || !is_writable($this->filepath)){
  49. if(!@mkdir($this->filepath, 0755)){
  50. $this->setOption('errorNum', -4);
  51. return false;
  52. }
  53. }
  54. return true;
  55. }
  56. //Used to check the size of file upload
  57. private function checkFileSize() {
  58. if($this->fileSize > $this->maxsize){
  59. $this->setOPtion('errorNum', '-2');
  60. return false;
  61. }else{
  62. return true;
  63. }
  64. }
  65. //Used to check the file upload type
  66. private function checkFileType() {
  67. if(in_array(strtolower($this->fileType), $this->allowtype)) {
  68. return true;
  69. } else{
  70. $this->setOption('errorNum', -1);
  71. return false;
  72. }
  73. }
  74. //Set the uploaded file name
  75. private function setNewFileName(){
  76. if($this-> israndname){
  77. $this->setOption('newFileName', $this->proRandName());
  78. } else {
  79. $this->setOption('newFileName', $this->originName);
  80. }
  81. }
  82. //Set a random file name
  83. private function proRandName(){
  84. $fileName=date("YmdHis").rand(100,999);
  85. return $fileName.'.'.$this->fileType;
  86. }
  87. private function setOption($key, $val){
  88. $this->$key=$val;
  89. }
  90. //Used to upload a file
  91. function uploadFile($fileField){
  92. $return=true;
  93. //Check the file upload path
  94. if(!$this->checkFilePath()){
  95. $this->errorMess=$this->getError();
  96. return false;
  97. }
  98. $name=$_FILES [$fileField]['name'];
  99. $tmp_name=$_FILES[$fileField]['tmp_name'];
  100. $size=$_FILES[$fileField]['size'];
  101. $error=$_FILES[$ fileField]['error'];
  102. if(is_Array($name)){
  103. $errors=array();
  104. for($i=0; $iif( $this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i])){
  105. if(!$this->checkFileSize() | | !$this->checkFileType()){
  106. $errors[]=$this->getError();
  107. $return=false;
  108. }
  109. }else{
  110. $error[]=$this-> getError();
  111. $return=false;
  112. }
  113. if(!$return)
  114. $this->setFiles();
  115. }
  116. if($return){
  117. $fileNames=array();
  118. for($ i=0; $iif($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error [$i])){
  119. $this->setNewFileName();
  120. if(!$this->copyFile()){
  121. $errors=$this->getError();
  122. $return=false;
  123. }else{
  124. $fileNames[]=$this->newFileName;
  125. }
  126. }
  127. }
  128. $this->newFileName=$fileNames;
  129. }
  130. $this->errorMess=$errors;
  131. return $return;
  132. } else {
  133. if($this->setFiles($name, $tmp_name, $size, $error)){
  134. if($this->checkFileSize() && $this->checkFileType()){
  135. $this->setNewFileName();
  136. if($this->copyFile()){
  137. return true;
  138. }else{
  139. $return=false;
  140. }
  141. }else{
  142. $return=false;
  143. }
  144. }else{
  145. $return=false;
  146. }
  147. if(!$return)
  148. $this->errorMess=$this->getError();
  149. return $return;
  150. }
  151. }
  152. private function copyFile(){
  153. if(!$this->errorNum){
  154. $filepath=rtrim($this->filepath, '/').'/';
  155. $filepath.=$this->newFileName;
  156. if(@move_uploaded_file($this->tmpFileName, $filepath)) {
  157. return true;
  158. }else{
  159. $this->setOption('errorNum', -3);
  160. return false;
  161. }
  162. }else{
  163. return false;
  164. }
  165. }
  166. //设置和$_FILES有关的内容
  167. private function setFiles($name="", $tmp_name='', $size=0, $error=0){
  168. $this->setOption('errorNum', $error);
  169. if($error){
  170. return false;
  171. }
  172. $this->setOption('originName', $name);
  173. $this->setOption('tmpFileName', $tmp_name);
  174. $arrStr=explode('.', $name);
  175. $this->setOption('fileType', strtolower($arrStr[count($arrStr)-1]));
  176. $this->setOption('fileSize', $size);
  177. return true;
  178. }
  179. //用于获取上传后文件的文件名
  180. function getNewFileName(){
  181. return $this->newFileName;
  182. }
  183. //上传如果失败,则调用这个方法,就可以查看错误报告
  184. function getErrorMsg() {
  185. return $this->errorMess;
  186. }
  187. }
复制代码
装好, 上传文件, php


Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles