search
HomeBackend DevelopmentPHP TutorialPHP image upload class code_PHP tutorial
PHP image upload class code_PHP tutorialJul 21, 2016 pm 03:45 PM
classhttpphpuploadcodepicturecopyofSimplekind

Let’s start with a simple one:

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 it
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 For image 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 names
$thisDir=$this->directory.$pathSign.$createFileName.".".$createFileType;
if(@move_uploaded_file($this->fileTemp,$thisDir)) //Move the temporary file Move to the specified path
{
return $thisDir;
}
}
}else{ //Image upload
$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; //Permissions 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") //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="Upload file appears Error";
//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="Image 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 image format is incorrect";
parent:: showError();
}
}
return true;
}
}
}
?>

Let’s take a more complicated PHP upload class that can automatically generate thumbnails.
Start the first step:
Create a folder, layout:
annex: attachment (uploaded files are stored in this directory Original image)
|— smallimg: stores thumbnail images
|— mark: stores watermark images
include: stores class files and fonts (this program code uses: 04B_08__.TTF)
| — upfile.php: Integrate simple upload, generate class file information of thumbnails and watermarks
|— 04B_08__.TTF: font file
test.php: test file
The second step is to upload the 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 placed in a subdirectory under $annexFolder, the default is: smallimg
var $markFolder = "mark";//Watermark image storage location
var $upFileType = "jpg gif png ";//Upload type, the default is: jpg gif png rar zip
var $upFileMax = 1024;//Upload size limit, the unit is "KB", the default is: 1024KB
var $fontType;// Font
var $maxWidth = 500; //Maximum image width
var $maxHeight = 600; //Maximum image height
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 to the image name
if(@empty($_FILES[$inputName]["name"])) die(error(" There is no image information uploaded, please confirm"));
$name = explode(".",$_FILES[$inputName]["name"]);//Separate the files before uploading with "." to obtain the files Type
$imgCount = count($name);//Get the number of interceptions
$imgType = $name[$imgCount-1];//Get the type of file
if(strpos($this- >upFileType,$imgType) === false) die(error("The uploaded 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("The 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 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 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;
}
}
?>

第三步:测试上传类
test.php
复制代码 代码如下:

$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;//设置生成水印图像值
$img->toFile = true;
$newSmallImg = $img->smallImg($photo);
$newMark = $img->waterMark($photo,$text);
echo "PHP image upload class code_PHP tutorial

";
echo "PHP image upload class code_PHP tutorial

";
echo "继续上传";
} else {
?>






}
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/320288.htmlTechArticle先来个简单的: 复制代码 代码如下: ? //http://www.jb51.net class upLoad{ public $length; //限定文件大小 public $file; //判断此类是用于图片上传还是文件...
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)