PHP image upload Class code, function is also more complete, we need to choose according to needs. Let's start with a simple:
?
Http://www.jzxue.com
Class upload{
Public $length; Qualify File Size
public $file; Determine if this class is for picture uploads or file uploads
Public $fileName; Filename
Public $fileTemp; Uploading Temporary files
Public $fileSize; Upload file size
Public $error; Upload file is wrong, PHP4 did not
Public $fileType; Upload file type
Public $directory; //
Public $maxLen;
Public $errormsg;
function __construct ($length, $file =true, $directory)
{
$this->maxlen= $length;
$this->length= $length *1024;
$this->file= $file; True to general file, false to picture's judgment
$this->directory= $directory;
}
Public Function UploadFile ($fileField)
{
$this->filename= $fileField [' name '];
$this->filetemp= $fileField [' Tmp_name '];
$this->error= $fileField [' Error '];
$this->filetype= $fileField [' type '];
$this->filesize= $fileField [' size '];
$pathSign = Directory_separator; // /
if ($this->file)//general file Upload
{
$path = $this->_iscreateddir ($this->directory);//Get Path
if ($path)//http://www.jzxue.com
{
$createFileType = $this->_getfiletype ($this->filename);//Set file category
$createFileName =uniqid (rand ()); Randomly generate file name
$thisDir = $this->directory. $pathSign. $createFileName. ".". $createFileType;
if (@move_uploaded_file ($this->filetemp, $thisDir))//move temporary files to the specified path
{
return $thisDir;
}
}
}else{//Picture upload
$path = $this->_iscreateddir ($this->directory);//Get Path
if ($path)//path exists//http://www.jzxue.com
{
$createFileType = $this->_getfiletype ($this->filename);//Set file category
$createFileName =uniqid (rand ());
Return @move_uploaded_file ($this->filetemp, $this->directory. $pathSign. $createFileName. ". $createFileType)? True:false;
}
}
}
Public Function _isbig ($length, $fsize)//Returns whether the file exceeds the specified size
{
return $fsize > $length? True:false;
}
Public Function _getfiletype ($fileName)//Get file suffix
{
Return End (Explode (".", $fileName));
}
Public Function _isimg ($fileType)//upload picture type is allowed
{
$type =array ("JPEG", "gif", "JPG", "BMP");
$fileType =strtolower ($fileType);
$fileArray =explode ("/", $fileType);
$file _type=end ($fileArray);
Return In_array ($file _type, $type);//http://www.jzxue.com
}
Public Function _iscreateddir ($path)//path exists and is created without
{
if (!file_exists ($path))
{
Return @mkdir ($path, 0755) True:false; Permission 755//
}
Else
{
return true;
}
}
Public Function ShowError ()//Display error message
{//http://www.jzxue.com
echo "<script Language = ' JavaScript ' >\n history.back (); \ alert (' $this->errormsg '); \ n </Script> \ n";
Exit ();
}
}
Class Multiupload extends upload{
Public $FILES;
function __construct ($arrayFiles, $length, $file =true, $directory)
{
$this->files= $arrayFiles;
Parent::__construct ($length, $file, $directory);
}
function Uploadmultifile ()
{
$arr =array ();
if ($this->_judge () $this->_judge () = "no")//file all meet the specifications, start uploading
{
foreach ($this->files as $key => $value)
{
$strDir =parent::uploadfile ($this->files[$key]);
Array_push ($arr, $strDir);
}
return $arr;
}else
{
return false;
}
}
function _judge ()
{
if ($this->file)
{
foreach ($this->files as $key => $value)
{
if ($this->_isbig ($this->length, $value [' Size '])
{
$this->errormsg= "file over $this->maxlen K";
Parent::showerror ();
}
if ($value [' Error ']=upload_err_no_file]
{
$this->errormsg= "Error uploading Files";
Parent::showerror ();
Return "No";
}
}
return true;
}else
{
Http://www.jzxue.com
foreach ($this->files as $key => $value)
{
if ($this->_isbig ($this->length, $value [' Size '])
{
$this->errormsg= "picture over $this->maxlen";
Parent::showerror ();
}
if ($value [' Error ']!=0]
{
$this->errormsg= "Upload picture error";
Parent::showerror ();
}
if (! $this->_isimg ($value [' type '])
{
$this->errormsg= "Picture format is wrong";
Parent::showerror ();
}
}
return true;
}
}
}
?>
A more complex, PHP upload class that can automatically generate thumbnails of features
Start the first step:
To create a folder, layout:
Annex: Attachment (the original image to be uploaded under this catalogue)
-smallimg: Storing thumbnail images
-mark: Storing watermark Picture
Include: Hold class file, font (this program code is used: 04b_08__. TTF)
-upfile.php: Integrated simple upload, generate thumbnails and watermark of class file information
-04b_08__. TTF: Font file
test.php: Test File
Second Step upload class
upfile.php
<?php
Class Upimages {
var $annexFolder = "Annex";//Attachment storage point, default: Annex
var $smallFolder = "smallimg";//thumbnail store path, note: Must be a subdirectory under the $annexFolder, default is: smallimg
var $markFolder = "Mark";//Watermark Image Store
var $upFileType = "jpg gif png";//type of upload, default: JPG gif png rar zip
var $upFileMax = 1024;//Upload size limit, the unit is "KB" and the default is: 1024KB
var $fontType;//font
var $maxWidth = 500; Picture Maximum width
var $maxHeight = 600; Picture Max height
function Upimages ($annexFolder, $smallFolder, $includeFolder) {
$this->annexfolder = $annexFolder;
$this->smallfolder = $smallFolder;
$this->fonttype = $includeFolder. " /04b_08__. TTF ";
}
function UpLoad ($inputName) {
$imageName = time ();//set current times to picture name
if (@empty ($_files[$inputName] ["name"]) Die (Error ("Do not upload picture information, please confirm"));
$name = Explode (".", $_files[$inputName] ["name"]);//will be uploaded before the file with "." Get file types separately
$imgCount = count ($name);//number of intercepts obtained
$imgType = $name [$imgCount -1];//gets the type of file
if (Strpos ($this->upfiletype, $imgType) = = False) die (Error ("Upload file type support only". $this->upfiletype. "Unsupported". $imgType));
$photo = $imageName. ". $imgType//file name written to the database
$uploadFile = $this->annexfolder. " /". $photo;//file name after upload
$upFileok = Move_uploaded_file ($_files[$inputName] ["Tmp_name"], $uploadFile);
if ($upFileok) {
$imgSize = $_files[$inputName] ["size"];
$kSize = Round ($imgSize/1024);
if ($kSize > ($this->upfilemax*1024)) {
@unlink ($uploadFile);
Die Error ("Upload file over". $this->upfilemax. " KB "));
}
} else {
Die ("Upload image failed, please make sure your upload file does not exceed $upFileMax KB or upload time timeout"));
}
return $photo;
}
function GetInfo ($photo) {
$photo = $this->annexfolder. " /". $photo;
$imageInfo = getimagesize ($photo);
$imgInfo ["width"] = $imageInfo [0];
$imgInfo ["height"] = $imageInfo [1];
$imgInfo ["type"] = $imageInfo [2];
$imgInfo ["name"] = basename ($photo);
return $imgInfo;
}
function smallimg ($photo, $width =128, $height =128) {
$imgInfo = $this->getinfo ($photo);
$photo = $this->annexfolder. " /". $photo;//Get Picture source
$newName = substr ($imgInfo ["Name"],0,strrpos ($imgInfo ["name"], "."). " _thumb.jpg ";//New picture name
if ($imgInfo ["type"] = = 1) {
$img = Imagecreatefromgif ($photo);
} elseif ($imgInfo [' type] = = 2) {
$img = Imagecreatefromjpeg ($photo);
} elseif ($imgInfo [' type] = = 3) {
$img = Imagecreatefrompng ($photo);
} else {
$img = "";
}
if (empty ($img)) return False;
$width = ($width > $imgInfo ["width"])? $imgInfo ["width"]: $width;
$height = ($height > $imgInfo ["height"])? $imgInfo ["Height"]: $height;
$srcW = $imgInfo ["width"];
$srcH = $imgInfo ["Height"];
if ($srcW * $width > $srcH * $height) {
$height = Round ($srcH * $width/$srcW);
} else {
$width = Round ($srcW * $height/$srcH);
}
if (function_exists ("Imagecreatetruecolor")) {
$NEWIMG = Imagecreatetruecolor ($width, $height);
Imagecopyresampled ($NEWIMG, $img, 0, 0, 0, 0, $width, $height, $imgInfo ["width"], $imgInfo ["height"]);
} else {
$NEWIMG = Imagecreate ($width, $height);
Imagecopyresized ($NEWIMG, $img, 0, 0, 0, 0, $width, $height, $imgInfo ["width"], $imgInfo ["height"]);
}
if ($this->tofile) {
if (file_exists ($this->annexfolder.) /". $this->smallfolder." /". $newName)) @unlink ($this->annexfolder.) /". $this->smallfolder." /". $newName);
Imagejpeg ($NEWIMG, $this->annexfolder. " /". $this->smallfolder." /". $newName);
return $this->annexfolder. " /". $this->smallfolder." /". $newName;
} else {
Imagejpeg ($NEWIMG);
}
Imagedestroy ($NEWIMG);
Imagedestroy ($IMG);
return $newName;
}
function watermark ($photo, $text) {
$imgInfo = $this->getinfo ($photo);
$photo = $this->annexfolder. " /". $photo;
$newName = substr ($imgInfo ["name"], 0, Strrpos ($imgInfo ["name"], "."). "_mark.jpg";
Switch ($imgInfo [' type]]) {
Case 1:
$img = Imagecreatefromgif ($photo);
Break
Case 2:
$img = Imagecreatefromjpeg ($photo);
Break
Case 3:
$img = Imagecreatefrompng ($photo);
Break
Default
return False;
}
if (empty ($img)) return False;
$width = ($this->maxwidth > $imgInfo ["width"])? $imgInfo ["width"]: $this->maxwidth;
$height = ($this->maxheight > $imgInfo ["height"])? $imgInfo ["Height"]: $this->maxheight;
$srcW = $imgInfo ["width"];
$srcH = $imgInfo ["Height"];
if ($srcW * $width > $srcH * $height) {
$height = Round ($srcH * $width/$srcW);
} else {
$width = Round ($srcW * $height/$srcH);
}
if (function_exists ("Imagecreatetruecolor")) {
$NEWIMG = Imagecreatetruecolor ($width, $height);
Imagecopyresampled ($NEWIMG, $img, 0, 0, 0, 0, $width, $height, $imgInfo ["width"], $imgInfo ["height"]);
} else {
$NEWIMG = Imagecreate ($width, $height);
Imagecopyresized ($NEWIMG, $img, 0, 0, 0, 0, $width, $height, $imgInfo ["width"], $imgInfo ["height"]);
}
$white = Imagecolorallocate ($newImg, 255, 255, 255);
$black = imagecolorallocate ($newImg, 0, 0, 0);
$alpha = Imagecolorallocatealpha ($newImg, 230, 230, 230, 40);
Imagefilledrectangle ($newImg, 0, $height -26, $width, $height, $alpha);
Imagefilledrectangle ($NEWIMG, $height -20, $height-7, $black);
Imagettftext ($NEWIMG, 4.9, 0, $height -14, $black, $this->fonttype, $text [0]);
Imagettftext ($NEWIMG, 4.9, 0, $height-6, $black, $this->fonttype, $text [1]);
if ($this->tofile) {
if (file_exists ($this->annexfolder.) /". $this->markfolder." /". $newName)) @unlink ($this->annexfolder.) /". $this->markfolder." /". $newName);
Imagejpeg ($NEWIMG, $this->annexfolder. " /". $this->markfolder." /". $newName);
return $this->annexfolder. " /". $this->markfolder." /". $newName;
} else {
Imagejpeg ($NEWIMG);
}
Imagedestroy ($NEWIMG);
Imagedestroy ($IMG);
return $newName;
}
}
?>
Step three: Test the upload class
test.php
<?php
$annexFolder = "Annex";
$smallFolder = "Smallimg";
$markFolder = "Mark";
$includeFolder = "include";
Require ("./". $includeFolder. " /upfile.php ");
$img = new Upimages ($annexFolder, $smallFolder, $includeFolder);
$text = Array ("www.jzxue.com", "All Rights reserved");
if (@$_get["Go"]) {
$photo = $img->upload ("Upfile");
$img->maxwidth = $img->maxheight = 350;//setting to generate watermark image values
$img->tofile = true;
$NEWSMALLIMG = $img->smallimg ($photo);
$newMark = $img->watermark ($photo, $text);
echo "<br><br> ';
echo "<br><br> ';
echo "<a href= './test.php ' > continue to upload </a>";
} else {
?>
<form method= "POST" action= "/test.php?go=go" enctype= "Multipart/form-data" >
<input type= "File" Name= "Upfile" ><br><br>
<input type= "Submit" value= "Upload" >
</form>
<?php
}
?>