PHP image upload class code_PHP tutorial
Let’s start with a simple one:
//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
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 "
";
echo "
";
echo "继续上传";
} else {
?>
}
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Validator can be created by adding the following two lines in the controller.
