search
HomeBackend DevelopmentPHP TutorialImplement multiple file upload php class_PHP tutorial

Implement multiple file upload php class_PHP tutorial

Jul 13, 2016 pm 04:56 PM
phpuploadBaseaccomplishapplicationdocumentyesofkindmeet

Multiple file upload is a basic application in PHP. It is a problem that PHPers will encounter anyway. Now I will introduce a fully functional and powerful multi-file upload class to everyone. There will be many places where this class can be used

.

The code is as follows Copy code

class Upload{
var $saveName;//save name
var $savePath;//save path
var $fileFormat = array('gif','jpg','doc','application/octet-stream');//File format & MIME limitation
var $overwrite = 0; // Overwrite mode
var $maxSize = 0;//Maximum bytes of file
var $ext; // File extension
var $thumb = 0; // Whether to generate thumbnails
var $thumbWidth = 130;//Thumbnail width
var $thumbHeight = 130;//Thumbnail height
var $thumbPrefix = "_thumb_"; // Thumbnail prefix
var $errno;// Error code
var $returnArray= array();//Return information of all files
var $returninfo= array(); // Return information for each file


//Constructor
// @param $savePath file save path
// @param $fileFormat file format limit array
// @param $maxSize Maximum file size
// @param $overwriet Whether to overwrite 1 allows overwriting 0 prohibits overwriting

function Upload($savePath, $fileFormat='',$maxSize = 0, $overwrite = 0) {
$this->setSavepath($savePath);
$this->setFileformat($fileFormat);
$this->setMaxsize($maxSize);
$this->setOverwrite($overwrite);
$this->setThumb($this->thumb, $this->thumbWidth,$this->thumbHeight);
$this->errno = 0;
}

// Upload
// @param $fileInput The name of the input in the web page Form
// @param $changeName Whether to change the file name
function run($fileInput,$changeName = 1){
if(isset($_FILES[$fileInput])){
$fileArr = $_FILES[$fileInput];
If(is_array($fileArr['name'])){//Upload multiple files with the same file domain name
for($i = 0; $i $ar['tmp_name'] = $fileArr['tmp_name'][$i];
$ar['name'] = $fileArr['name'][$i];
$ar['type'] = $fileArr['type'][$i];
$ar['size'] = $fileArr['size'][$i];
$ar['error'] = $fileArr['error'][$i];
$this->getExt($ar['name']);//Get the extension and assign it to $this->ext, it will be updated next time in the loop
        $this->setSavename($changeName == 1 ? '' : $ar['name']);//Set the save file name
If($this->copyfile($ar)){
$this->returnArray[] = $this->returninfo;
       }else{
$this->returninfo['error'] = $this->errmsg();
$this->returnArray[] = $this->returninfo;
}
}
Return $this->errno ? false : true;
}else{//Upload a single file
$this->getExt($fileArr['name']);//Get the extension
$this->setSavename($changeName == 1 ? '' : $fileArr['name']);//Set the save file name
If($this->copyfile($fileArr)){
$this->returnArray[] = $this->returninfo;
}else{
$this->returninfo['error'] = $this->errmsg();
$this->returnArray[] = $this->returninfo;
}
Return $this->errno ? false : true;
}
Return false;
}else{
$this->errno = 10;
Return false;
}
}

//Single file upload
// @param $fileArray file information array
function copyfile($fileArray){
$this->returninfo = array();
//Return information
$this->returninfo['name'] = $fileArray['name'];
$this->returninfo['md5'] = @md5_file($fileArray['tmp_name']);
$this->returninfo['saveName'] = $this->saveName;
$this->returninfo['size'] = number_format( ($fileArray['size'])/1024, 0, '.', ' ');//In KB
$this->returninfo['type'] = $fileArray['type'];
// Check file format
if (!$this->validateFormat()){
$this->errno = 11;
Return false;
}
// Check if the directory is writable
if(!@is_writable($this->savePath)){
$this->errno = 12;
Return false;
}
// If overwriting is not allowed, check if the file already exists
//if($this->overwrite == 0 && @file_exists($this->savePath.$fileArray['name'])){
// $this->errno = 13;
// return false;
//}
// If there is a size limit, check whether the file exceeds the limit
if ($this->maxSize != 0 ){
if ($fileArray["size"] > $this->maxSize){
$this->errno = 14;
Return false;
}
}
//File upload
if(!@move_uploaded_file($fileArray["tmp_name"], $this->savePath.$this->saveName)){
$this->errno = $fileArray["error"];
Return false;
}elseif( $this->thumb ){// Create thumbnail
$CreateFunction = "imagecreatefrom".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
$SaveFunction = "image".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
if (strtolower($CreateFunction) == "imagecreatefromgif"
&& !function_exists("imagecreatefromgif")) {
$this->errno = 16;
Return false;
} elseif (strtolower($CreateFunction) == "imagecreatefromjpeg"
&& !function_exists("imagecreatefromjpeg")) {
$this->errno = 17;
Return false;
} elseif (!function_exists($CreateFunction)) {
$this->errno = 18;
Return false;
}
 
$Original = @$CreateFunction($this->savePath.$this->saveName);
if (!$Original) {$this->errno = 19; return false;}
$originalHeight = ImageSY($Original);
$originalWidth = ImageSX($Original);
$this->returninfo['originalHeight'] = $originalHeight;
$this->returninfo['originalWidth'] = $originalWidth;
/*
if (($originalHeight thumbHeight
&& $originalWidth thumbWidth)) {
// If the thumbnail is smaller than expected, then Copy
Move_uploaded_file($this->savePath.$this->saveName,
$this->savePath.$this->thumbPrefix.$this->saveName);
} else {
If( $originalWidth > $this->thumbWidth ){// Width > Set width
$thumbWidth = $this->thumbWidth ;
$thumbHeight = $this->thumbWidth * ( $originalHeight / $originalWidth );
If($thumbHeight > $this->thumbHeight){// Height > Set height
$thumbWidth = $this->thumbHeight * ( $thumbWidth / $thumbHeight );
$thumbHeight = $this->thumbHeight ;
}
}elseif( $originalHeight > $this->thumbHeight ){// Height > Set height
$thumbHeight = $this->thumbHeight ;
     $thumbWidth = $this->thumbHeight * ( $originalWidth / $originalHeight );
     if($thumbWidth > $this->thumbWidth){// 宽 > 设定宽度
      $thumbHeight = $this->thumbWidth * ( $thumbHeight / $thumbWidth );
      $thumbWidth = $this->thumbWidth ;
     }
    }
    */
    $radio=max(($originalWidth/$this->thumbWidth),($originalHeight/$this->thumbHeight));
    $thumbWidth=(int)$originalWidth/$radio;
    $thumbHeight=(int)$originalHeight/$radio;

    if ($thumbWidth == 0) $thumbWidth = 1;
    if ($thumbHeight == 0) $thumbHeight = 1;
    $createdThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
    if ( !$createdThumb ) {$this->errno = 20; return false;}
    if ( !imagecopyresampled($createdThumb, $Original, 0, 0, 0, 0,
     $thumbWidth, $thumbHeight, $originalWidth, $originalHeight) )
     {$this->errno = 21; return false;}
    if ( !$SaveFunction($createdThumb,
     $this->savePath.$this->thumbPrefix.$this->saveName) )
     {$this->errno = 22; return false;}
   
  }
  // 删除临时文件
  /*
  if(!@$this->del($fileArray["tmp_name"])){
   return false;
  }
  */
  return true;
 }

// 文件格式检查,MIME检测
 function validateFormat(){
  if(!is_array($this->fileFormat)
   || in_array(strtolower($this->ext), $this->fileFormat)
   || in_array(strtolower($this->returninfo['type']), $this->fileFormat) )
   return true;
  else
   return false;
 }
// 获取文件扩展名
// @param $fileName 上传文件的原文件名
 function getExt($fileName){
  $ext = explode(".", $fileName);
  $ext = $ext[count($ext) - 1];
  $this->ext = strtolower($ext);
 }

// 设置上传文件的最大字节限制
// @param $maxSize 文件大小(bytes) 0:表示无限制
 function setMaxsize($maxSize){
  $this->maxSize = $maxSize;
 }
// 设置文件格式限定
// @param $fileFormat 文件格式数组
 function setFileformat($fileFormat){
  if(is_array($fileFormat)){$this->fileFormat = $fileFormat ;}
 }

// 设置覆盖模式
// @param overwrite 覆盖模式 1:允许覆盖 0:禁止覆盖
 function setOverwrite($overwrite){
  $this->overwrite = $overwrite;
 }


// 设置保存路径
// @param $savePath 文件保存路径:以 "/" 结尾,若没有 "/",则补上
 function setSavepath($savePath){
  $this->savePath = substr( str_replace("","/", $savePath) , -1) == "/"
  ? $savePath : $savePath."/";
 }

// 设置缩略图
// @param $thumb = 1 产生缩略图 $thumbWidth,$thumbHeight 是缩略图的宽和高
 function setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0){
  $this->thumb = $thumb;
  if($thumbWidth) $this->thumbWidth = $thumbWidth;
  if($thumbHeight) $this->thumbHeight = $thumbHeight;
 }

// 设置文件保存名
// @param $saveName 保存名,如果为空,则系统自动生成一个随机的文件名
 function setSavename($saveName){
  if ($saveName == ''){  // 如果未设置文件名,则生成一个随机文件名
   $name = date('YmdHis')."_".rand(100,999).'.'.$this->ext;
   //判断文件是否存在,不允许重复文件
   if(file_exists($this->savePath . $name)){
    $name = setSavename($saveName);
    }
  } else {
   $name = $saveName;
  }
  $this->saveName = $name;
 }

// 删除文件
// @param $fileName 所要删除的文件名
 function del($fileName){
  if(!@unlink($fileName)){
   $this->errno = 15;
   return false;
  }
  return true;
 }

// 返回上传文件的信息
 function getInfo(){
  return $this->returnArray;
 }

// 得到错误信息
 function errmsg(){
  $uploadClassError = array(
   0 =>'There is no error, the file uploaded with success. ',
   1 =>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
   2 =>'The uploaded file exceeds the MAX_FILE_SIZE that was specified in the HTML form.',
   3 =>'The uploaded file was only partially uploaded. ',
   4 =>'No file was uploaded. ',
   6 =>'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ',
   7 =>'Failed to write file to disk. Introduced in PHP 5.1.0. ',
   10 =>'Input name is not unavailable!',
   11 =>'The uploaded file is Unallowable!',
   12 =>'Directory unwritable!',
   13 =>'File exist already!',
   14 =>'File is too big!',
   15 =>'Delete file unsuccessfully!',
   16 =>'Your version of PHP does not appear to have GIF thumbnailing support.',
   17 =>'Your version of PHP does not appear to have JPEG thumbnailing support.',
   18 =>'Your version of PHP does not appear to have pictures thumbnailing support.',
   19 =>'An error occurred while attempting to copy the source image .
     Your version of php ('.phpversion().') may not have this image type support.',
   20 =>'An error occurred while attempting to create a new image.',
   21 =>'An error occurred while copying the source image to the thumbnail image.',
   22 =>'An error occurred while saving the thumbnail image to the filesystem.
     Are you sure that PHP has been configured with both read and write access on this folder?',
   );
  if ($this->errno == 0)
   return false;
  else
   return $uploadClassError[$this->errno];
 }
}

?>
如何使用这个类呢?

//如果收到表单传来的参数,则进行上传处理,否则显示表单
if(isset($_FILES['uploadinput'])){
 //建目录函数,其中参数$directoryName最后没有"/",
 //要是有的话,以'/'打散为数组的时候,最后将会出现一个空值
 function makeDirectory($directoryName) {
  $directoryName = str_replace("","/",$directoryName);
  $dirNames = explode('/', $directoryName);
  $total = count($dirNames) ;
  $temp = '';
  for($i=0; $i    $temp .= $dirNames[$i].'/';
   if (!is_dir($temp)) {
    $oldmask = umask(0);
    if (!mkdir($temp, 0777)) exit("不能建立目录 $temp");
    umask($oldmask);
   }
  }
  return true;
 }

if($_FILES['uploadinput']['name'] ""){
//Contains upload file class
require_once ('upload_class.php');
//Set the file upload directory
$savePath = "upload";
//Create directory
makeDirectory($savePath);
//Allowed file types
$fileFormat = array('gif','jpg','jpge','png');
//File size limit, unit: Byte, 1KB = 1000 Byte
//0 means no limit, but is affected by the upload_max_filesize setting in php.ini
$maxSize = 0;
//Overwrite the original file? 0 Not allowed 1 Allowed
$overwrite = 0;
//Initialize upload class
$f = new Upload( $savePath, $fileFormat, $maxSize, $overwrite);
//If you want to generate a thumbnail, call the member function $f->setThumb();
//Parameter list: setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0)
//$thumb=1 means to generate a thumbnail. When not called, its value is 0
//$thumbWidth Thumbnail width, unit is pixel (px), leave blank to use the default value 130
//$thumbHeight Thumbnail height, unit is pixel (px), if left blank, use the default value 130
$f->setThumb(1);

//The uploadinput in the parameter is the name of the input box for uploading files in the form
//The following 0 means the file name will not be changed. If it is 1, the system will generate a random file name
if (!$f->run('uploadinput',1)){
//You can only get the last error message through $f->errmsg(),
//Detailed information can be obtained in $f->getInfo().
echo $f->errmsg()."
n";
}
//The upload results are saved in the array returnArray.
echo "

";<br>
print_r($f->getInfo());<br>
echo "
";
}
}else{
?>

Send this file:










}

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631597.htmlTechArticleMultiple file upload is a basic application in PHP. It is a problem that PHPer will encounter anyway. Now I will introduce a function Let me give you a complete and powerful multi-file upload class, where you can use this class...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.