Home  >  Article  >  Backend Development  >  Share a PHP file upload class

Share a PHP file upload class

WBOY
WBOYOriginal
2016-07-25 08:52:07736browse
  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:
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