Home Backend Development PHP Tutorial A useful php file upload processing class

A useful php file upload processing class

Jul 25, 2016 am 09:08 AM

  1. //----------------------------------------
  2. // File description: File upload processing class
  3. // File author: Jesse Lee
  4. //--------------------------------- -------
  5. class upload {
  6. var $dir; //Physical directory where attachments are stored
  7. var $time; //Customized file upload time
  8. var $allow_types; //Allow attachment types to be uploaded
  9. var $field; //Upload control name
  10. var $maxsize; //Maximum allowed file size, unit is KB
  11. var $thumb_width; //Thumbnail width
  12. var $thumb_height; //Thumbnail height
  13. var $watermark_file; //Watermark image address
  14. var $watermark_pos; //Watermark position
  15. var $watermark_trans;//Watermark transparency
  16. //Constructor
  17. //$types: file types allowed to be uploaded, $maxsize: allowed size, $field: upload control name, $time : Custom upload time
  18. function upload($types = 'jpg|png', $maxsize = 1024, $field = 'attach', $time = '') {
  19. $this->allow_types = explode('|' ,$types);
  20. $this->maxsize = $maxsize * 1024;
  21. $this->field = $field;
  22. $this->time = $time ? $time : time();
  23. }
  24. //Set and create the directory where files are specifically stored
  25. //$basedir: base directory, must be a physical path
  26. //$filedir: custom subdirectory, available parameters {y}, {m}, {d}
  27. function set_dir ($basedir,$filedir = '') {
  28. $dir = $basedir;
  29. !is_dir($dir) && @mkdir($dir,0777);
  30. if (!empty($filedir)) {
  31. $filedir = str_replace(array('{y}','{m}','{y}'),array(date('Y',$this->time),date('m',$this-> time),date('d',$this->time)),strtolower($filedir));
  32. $dirs = explode('/',$filedir);
  33. foreach ($dirs as $d) {
  34. !empty($d) && $dir .= $d.'/';
  35. !is_dir($dir) && @mkdir($dir,0777);
  36. }
  37. }
  38. $this->dir = $dir;
  39. }
  40. //Picture thumbnail settings, no need to set if thumbnails are not generated
  41. //$width: thumbnail width, $height: thumbnail height
  42. function set_thumb ($width = 0, $height = 0) {
  43. $this->thumb_width = $width;
  44. $this->thumb_height = $height;
  45. }
  46. //Picture watermark settings, no need to set if no watermark is generated
  47. //$file: watermark picture, $pos: Watermark position, $trans: watermark transparency
  48. function set_watermark ($file, $pos = 6, $trans = 80) {
  49. $this->watermark_file = $file;
  50. $this->watermark_pos = $pos;
  51. $ this->watermark_trans = $trans;
  52. }
  53. /*---------------------------------------- ----------------------------
  54. Execute file upload, and after processing, return an array of file information containing upload success or failure,
  55. Among them: name is the file name. When the upload is successful, it is the file name uploaded to the server. If the upload fails, it is the local file name. dir is the physical path where the attachment is stored on the server. This value does not exist when the upload fails. Size is the size of the attachment. When uploading The value does not exist in case of failure
  56. flag is the status indicator, 1 means success, -1 means the file type is not allowed, -2 means the file size exceeds
  57. -------------------------- --------------------------------------------- */
  58. function execute () {
  59. $files = array(); //Successfully uploaded file information
  60. $field = $this->field;
  61. $keys = array_keys($_FILES[$field]['name']);
  62. foreach ($keys as $key) {
  63. if (!$_FILES[$field]['name'][$key]) continue;
  64. $fileext = $this->fileext($_FILES[$field][' name'][$key]); //Get the file extension
  65. $filename = $this->time.mt_rand(100,999).'.'.$fileext; //Generate the file name
  66. $filedir = $this- >dir; //The actual directory where attachments are stored
  67. $filesize = $_FILES[$field]['size'][$key]; //File size
  68. //File type not allowed
  69. if (!in_array($fileext ,$this->allow_types)) {
  70. $files[$key]['name'] = $_FILES[$field]['name'][$key];
  71. $files[$key]['flag' ] = -1;
  72. continue;
  73. }
  74. //File size exceeded
  75. if ($filesize > $this->maxsize) {
  76. $files[$key]['name'] = $_FILES[$field] ['name'][$key];
  77. $files[$key]['flag'] = -2;
  78. continue;
  79. }
  80. $files[$key]['name'] = $filename;
  81. $files[$key]['dir'] = $filedir;
  82. $files[$key]['size'] = $filesize;
  83. / /Save the uploaded file and delete the temporary file
  84. if (is_uploaded_file($_FILES[$field]['tmp_name'][$key])) {
  85. move_uploaded_file($_FILES[$field]['tmp_name'][$key], $filedir.$filename);
  86. @unlink($_FILES[$field]['tmp_name'][$key]);
  87. $files[$key]['flag'] = 1;
  88. //Add pictures Watermark and generate thumbnails
  89. if (in_array($fileext,array('jpg','png','gif'))) {
  90. if ($this->thumb_width) {
  91. if ($this->create_thumb ($filedir.$filename,$filedir.'thumb_'.$filename)) {
  92. $files[$key]['thumb'] = 'thumb_'.$filename; //Thumbnail file name
  93. }
  94. }
  95. $this->create_watermark($filedir.$filename);
  96. }
  97. }
  98. }
  99. return $files;
  100. }
  101. //Create thumbnail, generate thumbnail with the same extension
  102. //Php.aspx_file: source Image path, $thumb_file: Thumbnail path
  103. function create_thumb (Php.aspx_file,$thumb_file) {
  104. $t_width = $this->thumb_width;
  105. $t_height = $this->thumb_height;
  106. if (!file_exists(Php .aspx_file)) return false;
  107. Php.aspx_info = getImageSize(Php.aspx_file);
  108. //If the source image is less than or equal to the thumbnail, copy the source image as the thumbnail
  109. if (Php.aspx_info[0] <= $ t_width && Php.aspx_info[1] <= $t_height) {
  110. if (!copy(Php.aspx_file,$thumb_file)) {
  111. return false;
  112. }
  113. return true;
  114. }
  115. //Calculate thumbnails proportionally Size
  116. if (Php.aspx_info[0] - $t_width > Php.aspx_info[1] - $t_height) {
  117. $t_height = ($t_width / Php.aspx_info[0]) * Php.aspx_info[1];
  118. } else {
  119. $t_width = ($t_height / Php.aspx_info[1]) * Php.aspx_info[0];
  120. }
  121. //Get the file extension
  122. $fileext = $this->fileext(Php.aspx_file) ;
  123. switch ($fileext) {
  124. case 'jpg' :
  125. Php.aspx_img = ImageCreateFromJPEG(Php.aspx_file); break;
  126. case 'png' :
  127. Php.aspx_img = ImageCreateFromPNG(Php.aspx_file); break;
  128. case 'gif' :
  129. Php.aspx_img = ImageCreateFromGIF(Php.aspx_file); break;
  130. }
  131. //Create a true color thumbnail image
  132. $thumb_img = @ImageCreateTrueColor($t_width,$t_height);
  133. //ImageCopyResampled function The copied image has better smoothness, give priority to
  134. if (function_exists('imagecopyresampled')) {
  135. @ImageCopyResampled($thumb_img,Php.aspx_img,0,0,0,0,$t_width,$t_height,Php.aspx_info[ 0],Php.aspx_info[1]);
  136. } else {
  137. @ImageCopyResized($thumb_img,Php.aspx_img,0,0,0,0,$t_width,$t_height,Php.aspx_info[0],Php.aspx_info [1]);
  138. }
  139. //Generate thumbnails
  140. switch ($fileext) {
  141. case 'jpg' :
  142. ImageJPEG($thumb_img,$thumb_file); break;
  143. case 'gif' :
  144. ImageGIF($thumb_img, $thumb_file); break;
  145. case 'png' :
  146. ImagePNG($thumb_img,$thumb_file); break;
  147. }
  148. //Destroy the temporary image
  149. @ImageDestroy(Php.aspx_img);
  150. @ImageDestroy($thumb_img);
  151. return true;
  152. }
  153. //Add watermark to the picture
  154. //$file: The file to be watermarked
  155. function create_watermark ($file) {
  156. //Return if the file does not exist
  157. if (!file_exists($this->watermark_file) || ! file_exists($file)) return;
  158. if (!function_exists('getImageSize')) return;
  159. //Check the file types supported by GD
  160. $gd_allow_types = array();
  161. if (function_exists('ImageCreateFromGIF')) $ gd_allow_types['image/gif'] = 'ImageCreateFromGIF';
  162. if (function_exists('ImageCreateFromPNG')) $gd_allow_types['image/png'] = 'ImageCreateFromPNG';
  163. if (function_exists('ImageCreateFromJPEG')) $gd_allow_types[ 'image/jpeg'] = 'ImageCreateFromJPEG';
  164. //Get file information
  165. $fileinfo = getImageSize($file);
  166. $wminfo = getImageSize($this->watermark_file);
  167. if ($fileinfo[0] < ; $wminfo[0] || $fileinfo[1] < $wminfo[1]) return;
  168. if (array_key_exists($fileinfo['mime'],$gd_allow_types)) {
  169. if (array_key_exists($wminfo[' mime'],$gd_allow_types)) {
  170. //Create image from file
  171. $temp = $gd_allow_types[$fileinfo['mime']]($file);
  172. $temp_wm = $gd_allow_types[$wminfo['mime' ]]($this->watermark_file);
  173. //Watermark position
  174. switch ($this->watermark_pos) {
  175. case 1 : //Top left
  176. $dst_x = 0; $dst_y = 0; break;
  177. case 2: //Top center
  178. $dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = 0; break;
  179. case 3: //Top right
  180. $dst_x = $fileinfo[0 ]; $dst_y = 0; break;
  181. case 4 : //bottom left
  182. $dst_x = 0; $dst_y = $fileinfo[1]; break;
  183. case 5 : //bottom centered
  184. $dst_x = ($fileinfo[ 0] - $wminfo[0]) / 2; $dst_y = $fileinfo[1]; break;
  185. case 6: // Bottom right
  186. $dst_x = $fileinfo[0]-$wminfo[0]; $dst_y = $fileinfo[1]-$wminfo[1]; break;
  187. default : //random
  188. $dst_x = mt_rand(0,$fileinfo[0]-$wminfo[0]); $dst_y = mt_rand(0,$ fileinfo[1]-$wminfo[1]);
  189. }
  190. if (function_exists('ImageAlphaBlending')) ImageAlphaBlending($temp_wm,True); //Set the image blending mode
  191. if (function_exists('ImageSaveAlpha')) ImageSaveAlpha($temp_wm,True); //Save the complete alpha channel information
  192. //Add watermark to the image
  193. if (function_exists('imageCopyMerge')) {
  194. ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0 ,0,$wminfo[0],$wminfo[1],$this->watermark_trans);
  195. } else {
  196. ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0 ],$wminfo[1]);
  197. }
  198. //Save the image
  199. switch ($fileinfo['mime']) {
  200. case 'image/jpeg' :
  201. @imageJPEG($temp,$file);
  202. break;
  203. case 'image/png' :
  204. @imagePNG($temp,$file);
  205. break;
  206. case 'image/gif' :
  207. @imageGIF($temp,$file);
  208. break;
  209. }
  210. //Destroy Zero hour image
  211. @imageDestroy($temp);
  212. @imageDestroy($temp_wm);
  213. }
  214. }
  215. }
  216. //Get the file extension
  217. function fileext($filename) {
  218. return strtolower(substr(strrchr($filename ,'.'),1,10));
  219. }
  220. }
  221. ?>
Copy code

调用示例:

  1. if ($_GET['action'] == 'save') {
  2. $up = new upload();
  3. $up->set_dir(dirname(__FILE__).'/upload/','{y}/{m}');
  4. $up->set_thumb(100,80);
  5. $up->set_watermark(dirname(__FILE__).'/jblog/images/watermark.png',6,90);
  6. $fs = $up->execute();
  7. var_dump($fs);
  8. }
  9. ?>
  10. test
复制代码


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)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

See all articles