Home Backend Development PHP Tutorial Share a PHP file upload class

Share a PHP file upload class

Jul 25, 2016 am 08:52 AM

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

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.

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...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles