搜尋
首頁後端開發php教程实现多文件上传php类_PHP教程

实现多文件上传php类_PHP教程

Jul 13, 2016 pm 04:56 PM
php上傳基礎實現應用文件類別遇到

多文件上传是PHP中的一个基础应用,反正PHPer都会遇到的问题,现在就介绍一个功能完善、强大的多文件上传类给大家吧,能用上这个类的地方会很多

 代码如下 复制代码

class Upload{
 var $saveName;// 保存名
 var $savePath;// 保存路径
 var $fileFormat = array('gif','jpg','doc','application/octet-stream');// 文件格式&MIME限定
 var $overwrite = 0;// 覆盖模式
 var $maxSize = 0;// 文件最大字节
 var $ext;// 文件扩展名
 var $thumb = 0;// 是否生成缩略图
 var $thumbWidth = 130;// 缩略图宽
 var $thumbHeight = 130;// 缩略图高
 var $thumbPrefix = "_thumb_";// 缩略图前缀
 var $errno;// 错误代号
 var $returnArray= array();// 所有文件的返回信息
 var $returninfo= array();// 每个文件返回信息


// 构造函数
// @param $savePath 文件保存路径
// @param $fileFormat 文件格式限制数组
// @param $maxSize 文件最大尺寸
// @param $overwriet 是否覆盖 1 允许覆盖 0 禁止覆盖

 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;
 }

// 上传
// @param $fileInput 网页Form(表单)中input的名称
// @param $changeName 是否更改文件名
 function run($fileInput,$changeName = 1){
  if(isset($_FILES[$fileInput])){
   $fileArr = $_FILES[$fileInput];
   if(is_array($fileArr['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']);//取得扩展名,赋给$this->ext,下次循环会更新
     $this->setSavename($changeName == 1 ? '' : $ar['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{//上传单个文件
    $this->getExt($fileArr['name']);//取得扩展名
    $this->setSavename($changeName == 1 ? '' : $fileArr['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;
  }
 }

// 单个文件上传
// @param $fileArray 文件信息数组
 function copyfile($fileArray){
  $this->returninfo = array();
  // 返回信息
  $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, '.', ' ');//以KB为单位
  $this->returninfo['type'] = $fileArray['type'];
  // 检查文件格式
  if (!$this->validateFormat()){
   $this->errno = 11;
   return false;
  }
  // 检查目录是否可写
  if(!@is_writable($this->savePath)){
   $this->errno = 12;
   return false;
  }
  // 如果不允许覆盖,检查文件是否已经存在
  //if($this->overwrite == 0 && @file_exists($this->savePath.$fileArray['name'])){
  // $this->errno = 13;
  // return false;
  //}
  // 如果有大小限制,检查文件是否超过限制
  if ($this->maxSize != 0 ){
   if ($fileArray["size"] > $this->maxSize){
    $this->errno = 14;
    return false;
   }
  }
  // 文件上传
  if(!@move_uploaded_file($fileArray["tmp_name"], $this->savePath.$this->saveName)){
   $this->errno = $fileArray["error"];
   return false;
  }elseif( $this->thumb ){// 创建缩略图
   $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)) {
    // 如果比期望的缩略图小,那只Copy
    move_uploaded_file($this->savePath.$this->saveName,
     $this->savePath.$this->thumbPrefix.$this->saveName);
   } else {
    if( $originalWidth > $this->thumbWidth ){// 宽 > 设定宽度
     $thumbWidth = $this->thumbWidth ;
     $thumbHeight = $this->thumbWidth * ( $originalHeight / $originalWidth );
     if($thumbHeight > $this->thumbHeight){// 高 > 设定高度
      $thumbWidth = $this->thumbHeight * ( $thumbWidth / $thumbHeight );
      $thumbHeight = $this->thumbHeight ;
     }
    }elseif( $originalHeight > $this->thumbHeight ){// 高 > 设定高度
     $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'] ""){
  //包含上传文件类
  require_once ('upload_class.php');
  //设置文件上传目录
  $savePath = "upload";
  //创建目录
  makeDirectory($savePath);
  //允许的文件类型
  $fileFormat = array('gif','jpg','jpge','png');
  //文件大小限制,单位: Byte,1KB = 1000 Byte
  //0 表示无限制,但受php.ini中upload_max_filesize设置影响
  $maxSize = 0;
  //覆盖原有文件吗? 0 不允许  1 允许
  $overwrite = 0;
  //初始化上传类
  $f = new Upload( $savePath, $fileFormat, $maxSize, $overwrite);
  //如果想生成缩略图,则调用成员函数 $f->setThumb();
  //参数列表: setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0)
  //$thumb=1 表示要生成缩略图,不调用时,其值为 0
  //$thumbWidth  缩略图宽,单位是像素(px),留空则使用默认值 130
  //$thumbHeight 缩略图高,单位是像素(px),留空则使用默认值 130
  $f->setThumb(1);
  
  //参数中的uploadinput是表单中上传文件输入框input的名字
  //后面的0表示不更改文件名,若为1,则由系统生成随机文件名
  if (!$f->run('uploadinput',1)){
   //通过$f->errmsg()只能得到最后一个出错的信息,
   //详细的信息在$f->getInfo()中可以得到。
   echo $f->errmsg()."
n";
  }
  //上传结果保存在数组returnArray中。
  echo "

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

Send this file:










}

?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/631597.htmlTechArticle多文件上传是PHP中的一个基础应用,反正PHPer都会遇到的问题,现在就介绍一个功能完善、强大的多文件上传类给大家吧,能用上这个类的地...
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
PHP的當前狀態:查看網絡開發趨勢PHP的當前狀態:查看網絡開發趨勢Apr 13, 2025 am 12:20 AM

PHP在現代Web開發中仍然重要,尤其在內容管理和電子商務平台。 1)PHP擁有豐富的生態系統和強大框架支持,如Laravel和Symfony。 2)性能優化可通過OPcache和Nginx實現。 3)PHP8.0引入JIT編譯器,提升性能。 4)雲原生應用通過Docker和Kubernetes部署,提高靈活性和可擴展性。

PHP與其他語言:比較PHP與其他語言:比較Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

PHP與Python:核心功能PHP與Python:核心功能Apr 13, 2025 am 12:16 AM

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

PHP:網絡開發的關鍵語言PHP:網絡開發的關鍵語言Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP:許多網站的基礎PHP:許多網站的基礎Apr 13, 2025 am 12:07 AM

PHP成為許多網站首選技術棧的原因包括其易用性、強大社區支持和廣泛應用。 1)易於學習和使用,適合初學者。 2)擁有龐大的開發者社區,資源豐富。 3)廣泛應用於WordPress、Drupal等平台。 4)與Web服務器緊密集成,簡化開發部署。

超越炒作:評估當今PHP的角色超越炒作:評估當今PHP的角色Apr 12, 2025 am 12:17 AM

PHP在現代編程中仍然是一個強大且廣泛使用的工具,尤其在web開發領域。 1)PHP易用且與數據庫集成無縫,是許多開發者的首選。 2)它支持動態內容生成和麵向對象編程,適合快速創建和維護網站。 3)PHP的性能可以通過緩存和優化數據庫查詢來提升,其廣泛的社區和豐富生態系統使其在當今技術棧中仍具重要地位。

PHP中的弱參考是什麼?什麼時候有用?PHP中的弱參考是什麼?什麼時候有用?Apr 12, 2025 am 12:13 AM

在PHP中,弱引用是通過WeakReference類實現的,不會阻止垃圾回收器回收對象。弱引用適用於緩存系統和事件監聽器等場景,需注意其不能保證對象存活,且垃圾回收可能延遲。

解釋PHP中的__ Invoke Magic方法。解釋PHP中的__ Invoke Magic方法。Apr 12, 2025 am 12:07 AM

\_\_invoke方法允許對象像函數一樣被調用。 1.定義\_\_invoke方法使對象可被調用。 2.使用$obj(...)語法時,PHP會執行\_\_invoke方法。 3.適用於日誌記錄和計算器等場景,提高代碼靈活性和可讀性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器