亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Backend Development PHP Tutorial PHP image upload class; supports watermark-date folder-generated thumbnails, supports multiple file uploads

PHP image upload class; supports watermark-date folder-generated thumbnails, supports multiple file uploads

Jul 25, 2016 am 08:46 AM

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

Image upload, PHP
This topic was moved by Xiaobei on 2015-11-18 08:23


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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How to combine two php arrays unique values? How to combine two php arrays unique values? Jul 02, 2025 pm 05:18 PM

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

php regex for password strength php regex for password strength Jul 03, 2025 am 10:33 AM

To determine the strength of the password, it is necessary to combine regular and logical processing. The basic requirements include: 1. The length is no less than 8 digits; 2. At least containing lowercase letters, uppercase letters, and numbers; 3. Special character restrictions can be added; in terms of advanced aspects, continuous duplication of characters and incremental/decreasing sequences need to be avoided, which requires PHP function detection; at the same time, blacklists should be introduced to filter common weak passwords such as password and 123456; finally it is recommended to combine the zxcvbn library to improve the evaluation accuracy.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to create an array in php? How to create an array in php? Jul 02, 2025 pm 05:01 PM

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

See all articles