search
HomeBackend DevelopmentPHP TutorialCompletely encapsulated php upload file class

  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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment