国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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}377j5v51b 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}, 377j5v51b
  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}','377j5v51b'),array(date('Y',$this->time),date('m',$this->time),date(' d',$this->time)),strtolower($filedir));//Use string_replace to replace {y} {m} 377j5v51b 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)

What are some best practices for versioning a PHP-based API? What are some best practices for versioning a PHP-based API? Jun 14, 2025 am 12:27 AM

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

What are the differences between procedural and object-oriented programming paradigms in PHP? What are the differences between procedural and object-oriented programming paradigms in PHP? Jun 14, 2025 am 12:25 AM

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

What are weak references (WeakMap) in PHP, and when might they be useful? What are weak references (WeakMap) in PHP, and when might they be useful? Jun 14, 2025 am 12:25 AM

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

See all articles