search
HomeBackend DevelopmentPHP TutorialPHP image file upload class (can automatically generate thumbnails)

分享一个php图片上传类,且可以自动生成缩略图,有需要的朋友,可以作个参考,希望可以对您有用。

php实现的图片文件上传类,代码:

<?php
/**
功 能:文件上传类 支持文件夹自动分组保存;
创建类:参数(文件域,文件原名,文件大小);
$myupload = new upfileClass($upfile,$upfile_name,$upfile_size);
$myupload->savefile(); # 保存方法 并返回保存路径附带文件名;

@ echo MakeBuild($BuildFile,$newFile,$File_width);
生成指定文件的缩略图;
$myupload->MakeBuild("images/a.jpg","news/b.jpg","100");
*/

class upfileClass
{
var $upfile, $upfile_name, $upfile_size;

var $new_upfile_name;   # 上传后的文件名称 ; 
var $fleth, $fileExtent; # 文件扩展名(类型) ; 
var $f1, $f2, $f3;   # 文件保存路径(多级) upfiles/2008-01/08/;
var $filename;    # 文件(带路径) ;

var $maxSize, $File_type; # 允许上传文件的大小 允许上传文件的类型 ;

var $BuildFile,$newFile,$File_width,$File_height,$rate;

function upfileClass($upfile,$upfile_name,$upfile_size)
{
   $this->upfile = $upfile;
  $this->upfile_name = $upfile_name;
  $this->upfile_size = $upfile_size;
  
  $this->new_upfile_name = $this->CreateNewFilename($this->upfile_name);
  
  $this->f1 = "upfiles";
  $this->f2 = $this->f1."/".date('Y')."-".date('m');
$this->f3 = $this->f2."/".date('d');
  
  $this->filename = $this->f3 . "/" . $this->new_upfile_name;
  $this->maxSize = 500*1024;    # 文件大小 500KB
  $this->File_type = "gif/jpg/jpeg/png"; # 允许上传的文件类型
}

# 创建新文件名 (原文件名)
function CreateNewFilename($file_name)
{
   $this->fleth = explode(".",$file_name);
   $this->fileExtent = $this->fleth[(int)count($this->fleth)-1]; # 获取文件后缀;
   $tmpstr = date('YmdHis') . "." .$this->fileExtent;    # 创建新文件名;
   return $tmpstr;
}

# 检测文件类型是否正确
function chk_fileExtent()
{
   $iwTrue = 0;
   $fle = explode("/",$this->File_type);
   for($i=0; $i < count($fle); $i++){
    if( $this->fileExtent == $fle[$i] )
    {
     $iwTrue = (int) $iwTrue + 1;
    }
   }
   if( $iwTrue == 0 ){
    $this->msg("文件不符合 ".$this->File_type." 格式!");
   }
}

# 提示错误信息并终止操作
function msg($Error)
{
   echo "<script language=/"javascript/">/n";
   echo " alert('".$Error."');/n";
   echo " window.history.back();/n";
   echo "</script>/n";
   die();
}

# 保存文件
function savefile()
{
   $this->chk_fileExtent();
   $this->chk_fileSize();
   $this->CreateFolder( "../".$this->f1 );
   $this->CreateFolder( "../".$this->f2 );
   $this->CreateFolder( "../".$this->f3 );
   return $this->chk_savefile();
}

# 检测上传结果是否成功
function chk_savefile()
{
   $copymsg = copy($this->upfile,"../".$this->filename);
   if( $copymsg ){
    return $this->filename;
   }
   else{
    $this->msg("文件上传失败! /n/n请重新上传! ");
   }
}

# 创建文件夹
function CreateFolder($foldername)
{
   if( !is_dir($foldername) ){
    mkdir($foldername,0777);
   }
}

# 检测文件大小
function chk_fileSize()
{
   if( $this->upfile_size > $this->maxSize ){
    $this->msg("目标文件不能大于". $this->maxSize/1024 ." KB");
   }
}

# 删除文件($filePath 文件相对路径)
function Deletefile($filePath)
{
   if( !is_file($filePath) ){
    return false;
   }
   else{
    $ending = @unlink($filePath);
    return $ending;
   }
}

/*
   函数:生成缩略图
    MakeBuild("images/a.jpg","news/b.jpg","100");
   参数:
   echo $BuildFile;   原图 带路径
   echo $newFile;    生成的缩略图 带路径
   echo $File_width;   缩略图宽度值
   echo $File_height;   缩略图高度值 (默认为宽度的比例值)
   echo $rate;     缩略图象品质;
*/
function MakeBuild($BuildFile,$newFile,$File_width,$File_height=0,$rate=100) 
{ 
   if(!is_file($BuildFile)){
    $this->msg("文件 ".$BuildFile." 不是一个有效的图形文件!/n/n系统无法生成该文件的缩略图!");
    return false;
   }
   $data = GetImageSize($BuildFile); 
   switch($data[2]){ 
   case 1: 
    $im = @ImageCreateFromGIF($BuildFile); 
    break;
   case 2: 
    $im = @ImageCreateFromJPEG($BuildFile); 
    break;
   case 3: 
    $im = @ImageCreateFromPNG($BuildFile); 
    break;
   } 
   if(!$im){
    return false;
   }
   else{
    $srcW=ImageSX($im);  # 取得原图宽度;
    $srcH=ImageSY($im); # 取得原图高度;
    $dstX=0; 
    $dstY=0; 
   
    if($File_height==0){
     $File_height = $File_width/$srcW*$srcH;
    }
   
    if ($srcW*$File_height>$srcH*$File_width){ 
     $fFile_height = round($srcH*$File_width/$srcW); 
     $dstY = floor(($File_height-$fFile_height)/2); 
     $fFile_width = $File_width; 
    } 
    else { 
     $fFile_width = round($srcW*$File_height/$srcH); 
     $dstX = floor(($File_width-$fFile_width)/2); 
     $fFile_height = $File_height; 
    } 
    $ni = ImageCreateTrueColor($File_width,$File_height); 
    $dstX = ($dstX<0)?0:$dstX; 
    $dstY = ($dstX<0)?0:$dstY; 
    $dstX = ($dstX>($File_width/2))?floor($File_width/2):$dstX; 
    $dstY = ($dstY>($File_height/2))?floor($File_height/s):$dstY; 
    ImageCopyResized($ni,$im,$dstX,$dstY,0,0,$fFile_width,$fFile_height,$srcW,$srcH); 
   
    ImageJpeg($ni,$newFile,$rate); # 生成缩略图;
    imagedestroy($im);     # imagedestroy(resource) 释放image关联的内存
   }
} 

}
?>


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
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft