PHP file upload and upload pictures plus watermark example

Source: Internet
Author: User
Tags character set create directory file upload php file php file upload rand relative

Let's take a look at a simple file upload code.

HTML file (mainly the form of the form of the upload file forms)

The code is as follows Copy Code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">



<!--This line defines the character set, in the country that uses Chinese character, the character set usually has gb2312,utf-8 two kinds of character sets, set incorrectly will cause the page Chinese garbled

Because my editor is utf-8, I define the character set as Utf-8. If your character set is gb2312, you can modify the CharSet value-->

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>

<!--This trip is due to the incompatibility of IE browser, the number of ie6,ie7 used is not much, most can ignore-->

<meta http-equiv= "x-ua-compatible" content= "Ie=emulateie7"/>

<!--define Document title-->

<title>php Upload Example </title>

<!--Add JS script, simple front end judgment, prevent not to choose to upload file to click Submit-->

<script type= "Text/javascript" >

Execute the INSIDE function body when the page is loaded

Because the loading order of the page is from top to bottom, otherwise you can move JS to the footer

Window.onload = function () {

Add a mouse click event to the Upload button

Document.forms[0].elements[1].onclick = function () {

Determine if the file name you want to upload is empty

if (Document.forms[0].file.value = = "") {

Eject a warning if it is empty

Alert (' Please select File First ');

End Script Run

Return

}



Upload files If the file is not empty

Document.forms[0].submit ();

}

}

</script>


<body>

<!--this line defines form form area, upload file must be post, and add enctype= "Multipart/form-data" attribute

The value in action is the page where you want to process the uploaded file, or you can use the URL or relative path-->

<form action= "upload.php" method= "post" enctype= "Multipart/form-data" >

<!--define a browse form for a selection file the value in the Values property is the value displayed on the button-->

<input type= "file" name= "filename" value= "Select files to upload"/>

<!--define the value in the button Value property that is submitted to the server is the value displayed on the button-->

<input type= "button" value= "Upload"/>

</form>

</body>

PHP Upload processing file

The code is as follows Copy Code
<?php

/**

* PHP File Upload processing page

* Jones Taiwan Blog

*/



To define a hint function

Function alert ($msg) {

Return ' <script type= "Text/javascript" >alert ("'. $msg. '); Window.history.back ( -1);</script> ';

}



To define the allowed file types

$allowType = Array (' Image/jpeg ', ' image/gif ', ' image/jpg ');



Defines a path, either an absolute path, or a relative path can be

$filePath = './uploadfiledir/';



Receive form information The file value written inside is the name value in the static page form form

$file = $_files[' file '];



The first step is to determine whether the uploaded files have errors

if ($file [' ERROR ']!== 0) {

Exit (Alert (' File upload error '));

}



The second step is to determine the file size, where 102400 is byte, converted to KB is 100KB

if ($file [' Size '] > 102400) {

Exit (Alert (' File too large '));

}



The third step is to determine the file type

if (!in_array (Mime_content_type ($file [' tmp_name ']), $allowType)) {

Exit (Alert (' File type error '));

}



The fourth step is to determine if the path exists, and if it does not exist, create

if (!file_exists ($filePath) &&!mkdir ($filePath, 0777,true)) {

Exit (Alert (' Create directory error '));

}



Step fifth, define the name and path after uploading

$filename = Time (). ' _ '. $file [' name '];



Step sixth, copy the file

if (!copy ($file [' Tmp_name '], $filePath. $filename)) {

Exit (' Upload file error, please try again ');

}



Step seventh, delete temporary files

Unlink ($file [' tmp_name ']);



Prompt upload Success

echo alert (' Congratulations, upload file ['. $filename. '] Success! ');



Note: If you have other table field names in the upload we need to take advantage of the post to accept it, otherwise you may not accept the value.

After you complete the above steps, you will be able to add a watermark to your uploaded images. Here's a little demo I wrote.
Watermark Class

The code is as follows Copy Code

<?php
/**
* Add Watermark Class
* Jones Taiwan Blog
*/

Class water{

Private $imgPath; Picture path

Public function __construct ($imgPath = "./") {
$this->imgpath = RTrim ($imgPath, "/"). " /";
}

Write Watermark Action
Public Function Waterinfo ($ground, $water, $pos =0, $prefix = "Lee_", $tm =50) {
$allPathGround = $this->imgpath. $ground;
$allPathWater = $this->imgpath. $water;
$groundInfo = $this->imginfo ($allPathGround);
$waterInfo = $this->imginfo ($allPathWater);

Determine if the watermark image is larger than the original
if (! $newPos = $this->imgpos ($groundInfo, $waterInfo, $pos)) {
echo "Your watermark picture is bigger than the original";
return false;
}

Open Resource
$groundRes = $this->imgres ($allPathGround, $groundInfo [' mime ']);
$waterRes = $this->imgres ($allPathWater, $waterInfo [' mime ']);

Consolidating resources
$newGround = $this->imgcopy ($groundRes, $waterRes, $newPos, $waterInfo, $TM);

Save Resources
$this->saveimg ($newGround, $ground, $groundInfo [' MIME '], $prefix);

}

Private Function Saveimg ($img, $ground, $info, $prefix) {
$path = $this->imgpath. $prefix. $ground;
Switch ($info) {
Case "Image/jpg":
Case "Image/jpeg":
Case "Image/pjpeg":
Imagejpeg ($img, $path);
Break
Case "Image/gif":
Imagegif ($img, $path);
Break
Case "Image/png":
Imagepng ($img, $path);
Break
Default
IMAGEGD2 ($img, $path);
}
}

Private Function Imgcopy ($ground, $water, $pos, $waterInfo, $tm) {
Imagecopymerge ($ground, $water, $pos [0], $pos [1],0,0, $waterInfo [0], $waterInfo [1], $TM);
return $ground;
}

Private Function Imgres ($img, $imgType) {
Switch ($imgType) {
Case "Image/jpg":
Case "Image/jpeg":
Case "Image/pjpeg":
$res =imagecreatefromjpeg ($IMG);
Break
Case "Image/gif":
$res =imagecreatefromgif ($IMG);
Break
Case "Image/png":
$res =imagecreatefrompng ($IMG);
Break
Case "Image/wbmp":
$res =imagecreatefromwbmp ($IMG);
Break
Default
$res =imagecreatefromgd2 ($IMG);
}
return $res;
}

Location is
1 Upper-Left 2 Upper 3 right
4 left Middle 5 Middle 6 right middle
7 lower left 8 lower 9 right lower
0 Random Positions
Private Function Imgpos ($ground, $water, $pos) {
if ($ground [0]< $water [0] | | $ground [1]< $water [1])//judging watermark and original image compare if watermark is higher or wider than the original The original youngster returns a fake
return false;
Switch ($pos) {
Case 1:
$x = 0;
$y = 0;
Break
Case 2:
$x =ceil (($ground [0]-$water [0])/2);
$y = 0;
Break
Case 3:
$x = $ground [0]-$water [0];
$y = 0;
Break
Case 4:
$x = 0;
$y =ceil (($ground [1]-$water [1])/2);
Break
Case 5:
$x =ceil (($ground [0]-$water [0])/2);
$y =ceil (($ground [1]-$water [1])/2);
Break
Case 6:
$x = $ground [0]-$water [0];
$y =ceil (($ground [1]-$water [1])/2);
Break
Case 7:
$x = 0;
$y = $ground [1]-$water [1];
Break
Case 8:
$x =ceil ($ground [0]-$water [0]/2);
$y = $ground [1]-$water [1];
Break
Case 9:
$x = $ground [0]-$water [0];
$y = $ground [1]-$water [1];
Break
Case 0:
Default
$x =rand (0, $ground [0]-$water [0]);
$y =rand (0, $ground [1]-$water [1]);
}
$xy []= $x;
$xy []= $y;
return $xy;
}

function to get picture information
Private Function Imginfo ($img) {
Return getimagesize ($IMG);
}
}
?>

Usage is very simple, let's introduce the principle, we just create a water class on it, very simple.

Example

The code is as follows Copy Code

if (!copy ($file [' Tmp_name '], $filePath. $filename)) {

Exit (' Upload file error, please try again ');

}

If the file is uploaded successfully we can do the following

  code is as follows copy code

$WT = new Sater ();
$water = ' a.gif ';//watermark Picture
$wt->waterinfo ($filePath. $filename, $water)//other default is OK.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.