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

Home Backend Development PHP Tutorial Image upload website php image upload class code

Image upload website php image upload class code

Jul 29, 2016 am 08:40 AM

Let’s do a simple one first:

Copy the code The code is as follows:


//http://www.jb51.net
class upLoad{
public $length; //Limit file size
public $file; //Determine whether this class is used for image upload or file upload
public $fileName; //File name
public $fileTemp; //Upload temporary file
public $fileSize; //Upload file size
public $error ; //Whether there is an error in uploading the file, php4 does not have
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 is a general file, false is a picture 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 the path
if($path)//http://www.jb51.net
{
$createFileType = $this->_getFileType($this->fileName);//Set the file category
$createFileName =uniqid(rand()); //Randomly generate file name
$thisDir=$this->directory.$pathSign.$createFileName.".".$createFileType;
if(@move_uploaded_file($this->fileTemp ,$thisDir)) //Move the temporary file to the specified path
{
return $thisDir;
}
}
}else{ //Upload the image
$path = $this->_isCreatedDir($this-> ;directory);//Get the path
if($path)//The path exists//http://www.jb51.net
{
$createFileType = $this->_getFileType($this->fileName); //Set the 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 the suffix of the file
{
return end(explode(".",$fileName));
}
public function _isImg($fileType) //Whether the uploaded image 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.jb51.net
}
public function _isCreatedDir($path) //Whether the path exists, create it if it does not exist
{
if(!file_exists ($path))
{
return @mkdir($path,0755)?true:false; //Permission 755//
}
else
{
return true;
}
}
public function showError() // Display error message
{//http://www.jb51.net
echo " 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") //If all files meet the specifications, start uploading
{
foreach($this->FILES as $key=>$value)
{
$strDir=parent::upLoadFile($this->FILES[$key]);
array_push($arr, $strDir);
}
//http://www.jb51.net
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 exceeds $this->maxLen K" ;
parent::showError();
}
if($value['error']=UPLOAD_ERR_NO_FILE)
{
//$this->errormsg="An error occurred while uploading the file";
//parent::showError ();
return "no";
}
}
return true;
}else
{
//http://www.jb51.net
foreach($this->FILES as $key=>$ value)
{
if($this->_isBig($this->length,$value['size']))
{
$this->errormsg="Picture exceeds $this->maxLen" ;
parent::showError();
}
if($value['error']!=0)
{
$this->errormsg="An error occurred while uploading the image";
parent::showError();
}
if(!$this->_isImg($value['type']))
{
$this->errormsg="The picture format is wrong";
parent::showError();
}
}
return true;
}
}
}
?>


Another more complicated PHP upload class that can automatically generate thumbnails
Start the first step:
Create a folder, layout:
annex: Attachment (the original uploaded image is stored in this directory)
|— smallimg: Store thumbnail images
|— mark: store watermark images
include: store class files and fonts (this program code uses: 04B_08__.TTF)
|— upfile.php: integrate simple upload, generate thumbnails and watermark classes File information
|— 04B_08__.TTF: font file
test.php: test file
Second step upload class
upfile.php

Copy code The code is as follows:


class UPImages {
var $annexFolder = "annex";//Attachment storage point, the default is: annex
var $smallFolder = "smallimg";//Thumbnail storage path, note: must be The subdirectory under $annexFolder, the default is: smallimg
var $markFolder = "mark"; //Watermark image storage location
var $upFileType = "jpg gif png"; //The upload type, the default is: jpg gif png rar zip
var $upFileMax = 1024; //Upload size limit, unit is "KB", default is: 1024KB
var $fontType; //Font
var $maxWidth = 500; //Maximum image width
var $maxHeight = 600; //Maximum height of image
function UPImages($annexFolder,$smallFolder,$includeFolder) {
$this->annexFolder = $annexFolder;
$this->smallFolder = $smallFolder;
$this->fontType = $includeFolder."/04B_08__.TTF";
}
function upLoad($inputName) {
$imageName = time();//Set the current time as the image name
if(@empty($_FILES[$inputName] ["name"])) die(error("No picture information uploaded, please confirm"));
$name = explode(".",$_FILES[$inputName]["name"]);//Will upload The previous files are separated by "." to get the file type
$imgCount = count($name);//Get the intercepted number
$imgType = $name[$imgCount-1];//Get the file type
if(strpos ($this->upFileType,$imgType) === false) die(error("The upload file type only supports ".$this->upFileType." does not support ".$imgType));
$photo = $ imageName.".".$imgType;//The file name written to the database
$uploadFile = $this->annexFolder."/".$photo;//The uploaded file name
$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("Uploaded file exceeds".$this->upFileMax."KB"));
}
} else {
die(error("Failed to upload image, please make sure your uploaded file does not exceed $upFileMax KB or the upload time has timed out"));
}
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 the 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, 13, $height-20, 15, $height-7, $black);
ImageTTFText($newImg, 4.9, 0, 20, $height-14, $black, $this->fontType, $text[0]);
ImageTTFText($newImg, 4.9, 0, 20, $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;
}
}
?>


第三步:測(cè)試上傳類(lèi)
test.php

復(fù)制代碼 代碼如下:


$annexFolder = "annex";
$smallFolder = "smallimg";
$markFolder = "mark";
$includeFolder = "include";
require("./".$includeFolder."/upfile.php");
$img = new UPImages($annexFolder,$smallFolder,$includeFolder);
$text = array("www.jb51.net","all rights reserved");
if(@$_GET["go"]) {
$photo = $img->upLoad("upfile");
$img->maxWidth = $img->maxHeight = 350;//設(shè)置生成水印圖像值
$img->toFile = true;
$newSmallImg = $img->smallImg($photo);
$newMark = $img->waterMark($photo,$text);
echo "

";
echo "

";
echo "繼續(xù)上傳";
} else {
?>







}
?>

以上就介紹了圖片上傳網(wǎng)站 php 圖片上傳類(lèi)代碼,包括了圖片上傳網(wǎng)站方面的內(nèi)容,希望對(duì)PHP教程有興趣的朋友有所幫助。

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)

Hot Topics

PHP Tutorial
1502
276
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.

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.

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.

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

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.

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

See all articles