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

A useful php file upload processing class

WBOY
WBOYOriginal
2016-07-25 09:08:09793browse
  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:
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
Previous article:miniSmarty Simple SmartyNext article:miniSmarty Simple Smarty