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

Home Backend Development PHP Tutorial Implementation code of PHP file upload class and image processing class

Implementation code of PHP file upload class and image processing class

Jul 25, 2016 am 09:00 AM

I will introduce to you the file uploading and image processing classes developed in PHP. Friends in need can refer to it and learn from it.

It is relatively simple to upload files in PHP. If there is another efficient PHP file upload class, it would be even more powerful, even if you don’t want to fly. So, what if there is another easy-to-use image processing class that can reduce images and add watermarks, wouldn’t it be more fun? I’m telling you in a low voice, that’s necessary, haha.

Let’s take a look at today’s php tutorial.

1. File upload code

<?php
/**
* 文件上傳類
* by bbs.it-home.org
*/
class uploadFile {
public $max_size = '1000000';//設置上傳文件大小
public $file_name = 'date';//重命名方式代表以時間命名,其他則使用給予的名稱
public $allow_types;//允許上傳的文件擴展名,不同文件類型用“|”隔開
public $errmsg = '';//錯誤信息
public $uploaded = '';//上傳后的文件名(包括文件路徑)
public $save_path;//上傳文件保存路徑
private $files;//提交的等待上傳文件
private $file_type = array();//文件類型
private $ext = '';//上傳文件擴展名
/**
* 構造函數,初始化類
* @access public
* @param string $file_name 上傳后的文件名
* @param string $save_path 上傳的目標文件夾
*/
public function __construct($save_path = './upload/',$file_name = 'date',$allow_types = '') {
$this->file_name = $file_name;//重命名方式代表以時間命名,其他則使用給予的名稱
$this->save_path = (preg_match('/\/$/',$save_path)) ? $save_path : $save_path . '/';
$this->allow_types = $allow_types == '' ? 'jpg|gif|png|zip|rar' : $allow_types;
}
/**
* 上傳文件
* @access public
* @param $files 等待上傳的文件(表單傳來的$_FILES[])
* @return boolean 返回布爾值
*/
public function upload_file($files) {
$name = $files['name'];
$type = $files['type'];
$size = $files['size'];
$tmp_name = $files['tmp_name'];
$error = $files['error'];
switch ($error) {
case 0 : $this->errmsg = '';
break;
case 1 : $this->errmsg = '超過了php.ini中文件大小';
break;
case 2 : $this->errmsg = '超過了MAX_FILE_SIZE 選項指定的文件大小';
break;
case 3 : $this->errmsg = '文件只有部分被上傳';
break;
case 4 : $this->errmsg = '沒有文件被上傳';
break;
case 5 : $this->errmsg = '上傳文件大小為0';
break;
default : $this->errmsg = '上傳文件失敗!';
break;
}
if($error == 0 && is_uploaded_file($tmp_name)) {
//檢測文件類型
if($this->check_file_type($name) == FALSE){
return FALSE;
}
//檢測文件大小
if($size > $this->max_size){
$this->errmsg = '上傳文件<font color=red>'.$name.'</font>太大,最大支持<font color=red>'.ceil($this->max_size/1024).'</font>kb的文件';
return FALSE;
}
$this->set_save_path();//設置文件存放路徑
$new_name = $this->file_name != 'date' ? $this->file_name.'.'.$this->ext : date('YmdHis').'.'.$this->ext;//設置新文件名
$this->uploaded = $this->save_path.$new_name;//上傳后的文件名
//移動文件
if(move_uploaded_file($tmp_name,$this->uploaded)){
$this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上傳成功!';
return TRUE;
}else{
$this->errmsg = '文件<font color=red>'.$this->uploaded.'</font>上傳失敗!';
return FALSE;
}
}
}
/**
* 檢查上傳文件類型
* @access public
* @param string $filename 等待檢查的文件名
* @return 如果檢查通過返回TRUE 未通過則返回FALSE和錯誤消息
*/
public function check_file_type($filename){
$ext = $this->get_file_type($filename);
$this->ext = $ext;
$allow_types = explode('|',$this->allow_types);//分割允許上傳的文件擴展名為數組
//echo $ext;
//檢查上傳文件擴展名是否在請允許上傳的文件擴展名中
if(in_array($ext,$allow_types)){
return TRUE;
}else{
$this->errmsg = '上傳文件<font color=red>'.$filename.'</font>類型錯誤,只支持上傳<font color=red>'.str_replace('|',',',$this->allow_types).'</font>等文件類型!';
return FALSE;
}
}
/**
* 取得文件類型
* @access public
* @param string $filename 要取得文件類型的目標文件名
* @return string 文件類型
*/
public function get_file_type($filename){
$info = pathinfo($filename);
$ext = $info['extension'];
return $ext;
}
/**
* 設置文件上傳后的保存路徑
*/
public function set_save_path(){
$this->save_path = (preg_match('/\/$/',$this->save_path)) ? $this->save_path : $this->save_path . '/';
if(!is_dir($this->save_path)){
//如果目錄不存在,創(chuàng)建目錄
$this->set_dir();
}
}
/**
* 創(chuàng)建目錄
* @access public
* @param string $dir 要創(chuàng)建目錄的路徑
* @return boolean 失敗時返回錯誤消息和FALSE
*/
public function set_dir($dir = null){
//檢查路徑是否存在
if(!$dir){
$dir = $this->save_path;
}
if(is_dir($dir)){
$this->errmsg = '需要創(chuàng)建的文件夾已經存在!';
}
$dir = explode('/', $dir);
foreach($dir as $v){
if($v){
$d .= $v . '/';
if(!is_dir($d)){
$state = mkdir($d, 0777);
if(!$state)
$this->errmsg = '在創(chuàng)建目錄<font color=red>' . $d . '時出錯!';
}
}
}
return true;
}
}
?>

2. Image processing code

<?php
/*************************************************
* 圖片處理類
*
* 可以對圖片進行生成縮略圖,打水印等操作
* 本類默認編碼為UTF8 如果要在GBK下使用請將img_mark方法中打中文字符串水印iconv注釋去掉
*
* 由于UTF8漢字和英文字母大小(像素)不好確定,在中英文混合出現(xiàn)太多時可能會出現(xiàn)字符串偏左
* 或偏右,請根據項目環(huán)境對get_mark_xy方法中的$strc_w = strlen($this->mark_str)*7+5進
* 行調整
* 需要GD庫支持,為更好使用本類推薦使用GD庫2.0+
*
* @author http://bbs.it-home.org
*************************************************/
class uploadImg extends uploadFile {
public $mark_str = 'bbs.it-home.org'; //水印字符串
public $str_r = 0; //字符串顏色R
public $str_g = 0; //字符串顏色G
public $str_b = 0; //字符串顏色B
public $mark_ttf = './upload/SIMSUN.TTC'; //水印文字字體文件(包含路徑)
public $mark_logo = './upload/logo.png'; //水印圖片
public $resize_h;//生成縮略圖高
public $resize_w;//生成縮略圖寬
public $source_img;//源圖片文件
public $dst_path = './upload/';//縮略圖文件存放目錄,不填則為源圖片存放目錄
/**
* 生成縮略圖 生成后的圖
* @access public
* @param integer $w 縮小后圖片的寬(px)
* @param integer $h 縮小后圖片的高(px)
* @param string $source_img 源圖片(路徑+文件名)
*/
public function img_resized($w,$h,$source_img = NULL){
$source_img = $source_img == NULL ? $this->uploaded : $source_img;//取得源文件的地址,如果為空則默認為上次上傳的圖片
if(!is_file($source_img)) { //檢查源圖片是否存在
$this->errmsg = '文件'.$source_img.'不存在';
return FALSE;
}
$this->source_img = $source_img;
$img_info = getimagesize($source_img);
$source = $this->img_create($source_img); //創(chuàng)建源圖片
$this->resize_w = $w;
$this->resize_h = $h;
$thumb = imagecreatetruecolor($w,$h);
imagecopyresized($thumb,$source,0,0,0,0,$w,$h,$img_info[0],$img_info[1]);//生成縮略圖片
$dst_path = $this->dst_path == '' ? $this->save_path : $this->dst_path; //取得目標文件夾路徑
$dst_path = (preg_match('/\/$/',$dst_path)) ? $dst_path : $dst_path . '/';//將目標文件夾后加上/
if(!is_dir($dst_path)) $this->set_dir($dst_path); //如果不存在目標文件夾則創(chuàng)建
$dst_name = $this->set_newname($source_img);
$this->img_output($thumb,$dst_name);//輸出圖片
imagedestroy($source);
imagedestroy($thumb);
}
/**
*打水印
*@access public
*@param string $source_img 源圖片路徑+文件名
*@param integer $mark_type 水印類型(1為英文字符串,2為中文字符串,3為圖片logo,默認為英文字符串)
*@param integer $mark_postion 水印位置(1為左下角,2為右下角,3為左上角,4為右上角,默認為右下角);
*@return 打上水印的圖片
*/
public function img_mark($source_img = NULL,$mark_type = 1,$mark_postion = 2) {
$source_img = $source_img == NULL ? $this->uploaded : $source_img;//取得源文件的地址,如果為空則默認為上次上傳的圖片
if(!is_file($source_img)) { //檢查源圖片是否存在
$this->errmsg = '文件'.$source_img.'不存在';
return FALSE;
}
$this->source_img = $source_img;
$img_info = getimagesize($source_img);
$source = $this->img_create($source_img); //創(chuàng)建源圖片
$mark_xy = $this->get_mark_xy($mark_postion);//取得水印位置
$mark_color = imagecolorallocate($source,$this->str_r,$this->str_g,$this->str_b);
switch($mark_type) {
case 1 : //加英文字符串水印
$str = $this->mark_str;
imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color);
$this->img_output($source,$source_img);
break;
case 2 : //加中文字符串水印
if(!is_file($this->mark_ttf)) { //檢查字體文件是否存在
$this->errmsg = '打水印失敗:字體文件'.$this->mark_ttf.'不存在!';
return FALSE;
}
$str = $this->mark_str;
//$str = iconv('gbk','utf-8',$str);//轉換字符編碼 如果使用GBK編碼請去掉此行注釋
imagettftext($source,12,0,$mark_xy[2],$mark_xy[3],$mark_color,$this->mark_ttf,$str);
$this->img_output($source,$source_img);
break;
case 3 : //加圖片水印
if(is_file($this->mark_logo)){ //如果存在水印logo的圖片則取得logo圖片的基本信息,不存在則退出
$logo_info = getimagesize($this->mark_logo);
}else{
$this->errmsg = '打水印失?。簂ogo文件'.$this->mark_logo.'不存在!';
return FALSE;
}
$logo_info = getimagesize($this->mark_logo);
if($logo_info[0]>$img_info[0] || $logo_info[1]>$img_info[1]) { //如果源圖片小于logo大小則退出
$this->errmsg = '打水印失?。涸磮D片'.$this->source_img.'比'.$this->mark_logo.'小!';
return FALSE;
}
$logo = $this->img_create($this->mark_logo);
imagecopy ( $source, $logo, $mark_xy[4], $mark_xy[5], 0, 0, $logo_info[0], $logo_info[1]);
$this->img_output($source,$source_img);
break;
default: //其它則為文字圖片
$str = $this->mark_str;
imagestring($source,5,$mark_xy[0],$mark_xy[1],$str,$mark_color);
$this->img_output($source,$source_img);
break;
}
imagedestroy($source);
}
/**
* 取得水印位置
* @access private
* @param integer $mark_postion 水印的位置(1為左下角,2為右下角,3為左上角,4為右上角,其它為右下角)
* @return array $mark_xy 水印位置的坐標(索引0為英文字符串水印坐標X,索引1為英文字符串水印坐標Y,
* 索引2為中文字符串水印坐標X,索引3為中文字符串水印坐標Y,索引4為水印圖片坐標X,索引5為水印圖片坐標Y)
*/
private function get_mark_xy($mark_postion){
$img_info = getimagesize($this->source_img);
$stre_w = strlen($this->mark_str)*9+5 ; //水印英文字符串的長度(px)(5號字的英文字符大小約為9px 為了美觀再加5px)
//(12號字的中文字符大小為12px,在utf8里一個漢字長度為3個字節(jié)一個字節(jié)4px 而一個英文字符長度一個字節(jié)大小大約為9px
// 為了在中英文混合的情況下顯示完全 設它的長度為字節(jié)數*7px)
$strc_w = strlen($this->mark_str)*7+5 ; //水印中文字符串的長度(px)
if(is_file($this->mark_logo)){ //如果存在水印logo的圖片則取得logo圖片的基本信息
$logo_info = getimagesize($this->mark_logo);
}
//由于imagestring函數和imagettftext函數中對于字符串開始位置不同所以英文和中文字符串的Y位置也有所不同
//imagestring函數是從文字的左上角為參照 imagettftext函數是從文字左下角為參照
switch($mark_postion){
case 1: //位置左下角
$mark_xy[0] = 5; //水印英文字符串坐標X
$mark_xy[1] = $img_info[1]-20;//水印英文字符串坐標Y
$mark_xy[2] = 5; //水印中文字符串坐標X
$mark_xy[3] = $img_info[1]-5;//水印中文字符串坐標Y
$mark_xy[4] = 5;//水印圖片坐標X
$mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印圖片坐標Y
break;
case 2: //位置右下角
$mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐標X
$mark_xy[1] = $img_info[1]-20;//水印英文字符串坐標Y
$mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐標X
$mark_xy[3] = $img_info[1]-5;//水印中文字符串坐標Y
$mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印圖片坐標X
$mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印圖片坐標Y
break;
case 3: //位置左上角
$mark_xy[0] = 5; //水印英文字符串坐標X
$mark_xy[1] = 5;//水印英文字符串坐標Y
$mark_xy[2] = 5; //水印中文字符串坐標X
$mark_xy[3] = 15;//水印中文字符串坐標Y
$mark_xy[4] = 5;//水印圖片坐標X
$mark_xy[5] = 5;//水印圖片坐標Y
break;
case 4: //位置右上角
$mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐標X
$mark_xy[1] = 5;//水印英文字符串坐標Y
$mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐標X
$mark_xy[3] = 15;//水印中文字符串坐標Y
$mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印圖片坐標X
$mark_xy[5] = 5;//水印圖片坐標Y
break;
default : //其它默認為右下角
$mark_xy[0] = $img_info[0]-$stre_w; //水印英文字符串坐標X
$mark_xy[1] = $img_info[1]-5;//水印英文字符串坐標Y
$mark_xy[2] = $img_info[0]-$strc_w; //水印中文字符串坐標X
$mark_xy[3] = $img_info[1]-15;//水印中文字符串坐標Y
$mark_xy[4] = $img_info[0]-$logo_info[0]-5;//水印圖片坐標X
$mark_xy[5] = $img_info[1]-$logo_info[1]-5;//水印圖片坐標Y
break;
}
return $mark_xy;
}
/**
* 創(chuàng)建源圖片
* @access private
* @param string $source_img 源圖片(路徑+文件名)
* @return img 從目標文件新建的圖像
*/
private function img_create($source_img) {
$info = getimagesize($source_img);
switch ($info[2]){
case 1:
if(!function_exists('imagecreatefromgif')){
$source = @imagecreatefromjpeg($source_img);
}else{
$source = @imagecreatefromgif($source_img);
}
break;
case 2:
$source = @imagecreatefromjpeg($source_img);
break;
case 3:
$source = @imagecreatefrompng($source_img);
break;
case 6:
$source = @imagecreatefromwbmp($source_img);
break;
default:
$source = FALSE;
break;
}
return $source;
}
/**
* 重命名圖片
* @access private
* @param string $source_img 源圖片路徑+文件名
* @return string $dst_name 重命名后的圖片名(路徑+文件名)
*/
private function set_newname($sourse_img) {
$info = pathinfo($sourse_img);
$new_name = $this->resize_w.'_'.$this->resize_h.'_'.$info['basename'];//將文件名修改為:寬_高_文件名
if($this->dst_path == ''){ //如果存放縮略圖路徑為空則默認為源文件同文件夾
$dst_name = str_replace($info['basename'],$new_name,$sourse_img);
}else{
$dst_name = $this->dst_path.$new_name;
}
return $dst_name;
}
/**
* 輸出圖片
* @access private
* @param $im 處理后的圖片
* @param $dst_name 輸出后的的圖片名(路徑+文件名)
* @return 輸出圖片
*/
public function img_output($im,$dst_name) {
$info = getimagesize($this->source_img);
switch ($info[2]){
case 1:
if(!function_exists('imagegif')){
imagejpeg($im,$dst_name);
}else{
imagegif($im, $dst_name);
}
break;
case 2:
imagejpeg($im,$dst_name);
break;
case 3:
imagepng($im,$dst_name);
break;
case 6:
imagewbmp($im,$dst_name);
break;
}
}
}
?>

That’s it. Regarding the principle of php file upload, you can take a look if you have time to better understand the above code.



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)

What are some best practices for versioning a PHP-based API? What are some best practices for versioning a PHP-based API? Jun 14, 2025 am 12:27 AM

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

What are the differences between procedural and object-oriented programming paradigms in PHP? What are the differences between procedural and object-oriented programming paradigms in PHP? Jun 14, 2025 am 12:25 AM

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

What are weak references (WeakMap) in PHP, and when might they be useful? What are weak references (WeakMap) in PHP, and when might they be useful? Jun 14, 2025 am 12:25 AM

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

See all articles