search
HomeBackend DevelopmentPHP TutorialPHP code to upload files and add text and image watermarks

  1. /***************************************

  2. Parameter description:
  3. $max_file_size: Upload file size limit, unit BYTE
  4. $destination_folder: Upload file path
  5. $watermark: Whether to attach a watermark (1 means adding watermark, others means not adding watermark);
  6. Instructions for use:

  7. 1. Change the PHP.INI file Remove the ; sign in front of the line "extension=php_gd2.dll" because we need to use the GD library;
  8. 2. Change extension_dir = to the directory where your php_gd2.dll is located;
  9. ************ ********/
  10. //Upload file type list

  11. $uptypes=array(
  12. 'image/jpg ',
  13. 'image/jpeg',
  14. 'image/png',
  15. 'image/pjpeg',
  16. 'image/gif',
  17. 'image/bmp',
  18. 'image/x-png'
  19. );
  20. $max_file_size=2000000; //About 2M, upload file size limit, unit BYTE

  21. $destination_folder="uploadimg/"; //Upload file path
  22. $watermark=1; //Whether to attach a watermark (1 is watermarked, others are not watermarked);
  23. $watertype=1; //Watermark type (1 is text, 2 is picture)
  24. $waterposition=1; //Watermark position (1 is the lower left corner, 2 is Lower right corner, 3 is the upper left corner, 4 is the upper right corner, 5 is the center);
  25. $waterstring="JYS studio"; //Watermark string
  26. $waterimg="xplore.gif";//Watermark image
  27. $imgpreview= 1; //Whether to generate a preview image (1 means generate, others do not generate);
  28. $imgpreviewsize=1/2; //Thumbnail ratio
  29. ?>
  30. <li><style type="text/css"><li><!--<li>body<li>{<li> font-size: 9pt;<li>}<li>input<li>{<li> background-color : yellow;<li> border: 1px inset #CCCCCC;<li>}<li>--><li></style></li> <li> <li> <li><form enctype="multipart/form-data" method="post" name="upform"> <li> Upload file:</li> <li> <input name="upfile" type="file"> </li> <li> <input type="submit" value="Upload"><br> </li> <li> The file types allowed to be uploaded are: =implode(', ',$uptypes)?> <!--Concatenate the elements in the uptypes array with ',' to form a string and return it--> </li> <li>< ;/form></li> <li> <?php <li>if ($_SERVER['REQUEST_METHOD'] == 'POST')</li> <li>{</li> <li> //Does the file exist? </li> <li> if (!is_uploaded_file($_FILES["upfile"][tmp_name]) )</li> <li> {</li> <li> echo "The picture does not exist!";</li> <li> exit;</li> <li> }</li> <li> $file = $_FILES["upfile"];</li> <li> //Check the file size</li> <li><p> if($max_file_size < ; $file["size"])</p></li> <li> {</li> <li> echo "The file is too big! Cannot exceed 2M! ";</li> <li> exit;</li> <li> }</li> <li><p> //Check the file type</p></li> <li> if(!in_array($file["type"], $uptypes))</li> <li> {</li> <li> echo "The file type does not match!" .$file["type"];</li> <li> exit;</li> <li> } </li> <li><p> //If the uploaded folder does not exist, it will be automatically created</p></li> <li> if(!file_exists($destination_folder))</li> <li> {</li> <li> mkdir ($destination_folder);</li> <li> }</li> <li><p> $filename=$file["tmp_name"]; //The temporary file name automatically generated by the system</p></li> <li> $filenamecustom = $file["name"]; / /The file name uploaded by the user</li> <li> $image_size = getimagesize($filename); //Image size</li> <li> $pinfo=pathinfo($file["name"]); //The path information of the uploaded file</li> <li> $ftype=$pinfo[' extension']; //The extension of the uploaded file</li> <li> //$destination = $destination_folder.time().".".$ftype;//The directory + file name + file type of the uploaded file, the file name is determined by time() Generate </li> <li> $destination = $destination_folder.$filenamecustom.".".$ftype;//Directory of uploaded file + user file name + file type</li> <li><p> //Check whether the file with the same name exists</p></li> <li> if (file_exists($destination) && $overwrite != true)</li> <li> {</li> <li> echo "The file with the same name already exists";</li> <li> exit;</li> <li> } </li> <li><p> //Move the file to the specified directory</p></li> <li> if( !move_uploaded_file ($filename, $destination))</li> <li> {</li> <li> echo "Error moving file";</li> <li> exit;</li> <li> }</li> <li><p> $pinfo=pathinfo($destination); //Upload to the server The path information of the file</p></li> <li> $fname=$pinfo[basename]; //The file name uploaded to the server</li> <li> // echo " <font color="red"> has been successfully uploaded!</font><br>File name: <font color="blue">".$destination_folder.$fname."</font><br>";</li> <li><p> / / echo " <font color="red"> Uploaded successfully! </font><br>File name: <font color="blue">".$destination."</font><br>";</p></li> <li> echo " <font color="red"> Uploaded successfully! </font><br>File name: <font color="blue">".$destination_folder.$filenamecustom."</font><br>";</li> <li> echo " Width:".$image_size[0 ];</li> <li> echo " length: ".$image_size[1];</li> <li> echo "<br> size: ".$file["size"]." bytes";</li> <li> if($watermark==1)</li> <li> {</li> <li> $iinfo=getimagesize($destination,$iinfo); //Get the image size and type</li> <li> $nimage=imagecreatetruecolor($image_size[0],$image_size[1]); //Create a true color image and return an image identifier Symbol, </li> <li> //Represents a black image of size x_size and y_size </li> <li> $white=imagecolorallocate($nimage,255,255,255); //nimage assigns color </li> <li> $black=imagecolorallocate($nimage,0,0,0). ;</li> <li> $red=imagecolorallocate($nimage,255,0,0);</li> <li> imagefill($nimage,0,0,$white); //The coordinates x, y of the nimage image (the upper left corner of the image is 0, 0) Use color color to perform area filling </li> <li> // (that is, points with the same color as the x, y point and adjacent points will be filled) </li> <li> /*</li> <li> 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5. = PSD, 6 = BMP, 7 = TIFF (intel byte order), 8 = TIFF (motorola byte order), </li> <li> 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM</li> <li> */ </li> <li> switch ($iinfo[2])</li> <li> {</li> <li> case 1:</li> <li> $simage =imagecreatefromgif($destination); //The image obtained from the given file name</li> <li> break;</li> <li> case 2:</li> <li> $simage =imagecreatefromjpeg($destination);</li> <li> break;</li> <li> case 3:</li> <li> $simage =imagecreatefrompng($destination);</li> <li> break;</li> <li> case 6:</li> <li> $simage =imagecreatefromwbmp($destination);</li> <li> break; </li> <li> default:</li> <li> die("Unsupported file type"); //Equivalent to exit()</li> <li> exit;</li> <li> }</li> <li> imagecopy($nimage,$simage,0,0,0,0,$image_size[0], $image_size[1]);//Copy simage starting from 0,0, $image_size[0] width, $image_size[1] height </li> <li> //Copy a part of simage to the position with coordinates 0,0 in nimage p></li> <li><p> imagefilledrectangle($nimage,1,$image_size[1]-15,80,$image_size[1],$white);//Draw an upper left corner coordinate of 1 in the nimage image with white color , $image_size[1]-15</p></li> <li> //Rectangle with lower right corner coordinates 80, $image_size[1]</li> <li> switch($watertype)</li> <li> {</li> <li> case 1: //Add watermark string</li> <li> imagestring($nimage,2, 3,$image_size[1]-15,$waterstring,$black);//Draw the waterstring in black to the 3,$image_size[1]-15 coordinates of nimage, and the font is the built-in font 2</li> <li> break;</li> <li> case 2 : //Add watermark image</li> <li> $simage1 =imagecreatefromgif("xplore.gif");</li> <li> imagecopy($nimage,$simage1,0,0,0,0,85,15);</li> <li> imagedestroy($simage1); // Release the memory associated with simagel</li> <li> break;</li> <li> }</li> <li> switch ($iinfo[2])</li> <li> {</li> <li> case 1:</li> <li> //imagegif($nimage, $destination);</li> <li> imagejpeg($nimage, $destination); // Creates a JPEG image with destination as the file name from the nimage image. The nimage parameter is the return value of the imagecreatetruecolor() function. </li> <li> break;</li> <li><p> case 2:</p></li> <li> imagejpeg($nimage, $destination);</li> <li> break;</li> <li><p> case 3:</p></li> <li> imagepng($nimage, $destination) );</li> <li> break;</li> <li><p> case 6:</p></li> <li> imagewbmp($nimage, $destination);</li> <li> //imagejpeg($nimage, $destination);</li> <li> break;</li> <li> }</li> <li> //Release memory </li> <li> imagedestroy($nimage);</li> <li> imagedestroy($simage);</li> <li> }</li> <li> if($imgpreview==1)</li> <li> {</li> <li> echo "<br>Image preview:<br>";</li> <li> echo "<img src="" . style="max-width:90%" height=".($image_size[1]*$imgpreviewsize);<li> echo " alt="Image preview:r File name: " time:>";</li> <li> }</li> <li>}</li> <li>?></li> <li> <li> <li> </form></li>
Copy code



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
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor