[PHP] php文件和图片上传类 →→→→→进入此内容的聊天室

来自 , 2021-02-20, 写在 PHP, 查看 121 次.
URL http://www.code666.cn/view/4e2a6330
  1. <?php
  2. //文件和图片上传类
  3. /*
  4.  使用方法:
  5.  function _upload($upload_dir){
  6.  $upload = new UploadFile();
  7.  //设置上传文件大小
  8.  $upload->maxSize=1024*1024*2;//最大2M
  9.  //设置上传文件类型
  10.  $upload->allowExts  = explode(',','jpg,gif,png,bmp');
  11.  
  12.  //设置附件上传目录
  13.  $upload->savePath ='../images/'.$upload_dir."/";
  14.  $upload->saveRule = cp_uniqid;
  15.  
  16.  if(!$upload->upload())
  17.  {
  18.  //捕获上传异常
  19.  $this->error($upload->getErrorMsg());
  20.  }
  21.  else
  22.  {
  23.  //取得成功上传的文件信息
  24.  return $upload->getUploadFileInfo();
  25.  }
  26.  }
  27.  */
  28. class UploadFile{
  29.  
  30.         // 上传文件的最大值
  31.         public $maxSize = -1;
  32.  
  33.         // 是否支持多文件上传
  34.         public $supportMulti = true;
  35.  
  36.         // 允许上传的文件后缀
  37.         //  留空不作后缀检查
  38.         public $allowExts = array();
  39.  
  40.         // 允许上传的文件类型
  41.         // 留空不做检查
  42.         public $allowTypes = array();
  43.  
  44.         // 使用对上传图片进行缩略图处理
  45.         public $thumb   =  false;
  46.         // 缩略图最大宽度
  47.         public $thumbMaxWidth;
  48.         // 缩略图最大高度
  49.         public $thumbMaxHeight;
  50.         // 缩略图前缀
  51.         public $thumbPrefix   =  'thumb_';
  52.         public $thumbSuffix  =  '';
  53.         // 缩略图保存路径
  54.         public $thumbPath = '';
  55.         // 缩略图文件名
  56.         public $thumbFile               =       '';
  57.         // 是否移除原图
  58.         public $thumbRemoveOrigin = false;
  59.         // 压缩图片文件上传
  60.         public $zipImages = false;
  61.         // 启用子目录保存文件
  62.         public $autoSub   =  false;
  63.         // 子目录创建方式 可以使用hash date
  64.         public $subType   = 'hash';
  65.         public $dateFormat = 'Ymd';
  66.         public $hashLevel =  1; // hash的目录层次
  67.         // 上传文件保存路径
  68.         public $savePath = '';
  69.         public $autoCheck = true; // 是否自动检查附件
  70.         // 存在同名是否覆盖
  71.         public $uploadReplace = false;
  72.  
  73.         // 上传文件命名规则
  74.         // 例如可以是 time uniqid com_create_guid 等
  75.         // 必须是一个无需任何参数的函数名 可以使用自定义函数
  76.         public $saveRule = '';
  77.  
  78.         // 上传文件Hash规则函数名
  79.         // 例如可以是 md5_file sha1_file 等
  80.         public $hashType = 'md5_file';
  81.  
  82.         // 错误信息
  83.         private $error = '';
  84.  
  85.         // 上传成功的文件信息
  86.         private $uploadFileInfo ;
  87.  
  88.         /**
  89.          +----------------------------------------------------------
  90.          * 架构函数
  91.          +----------------------------------------------------------
  92.          * @access public
  93.          +----------------------------------------------------------
  94.          */
  95.         public function __construct($maxSize='',$allowExts='',$allowTypes='',$savePath='',$saveRule='')
  96.         {
  97.                 if(!empty($maxSize) && is_numeric($maxSize)) {
  98.                         $this->maxSize = $maxSize;
  99.                 }
  100.                 if(!empty($allowExts)) {
  101.                         if(is_array($allowExts)) {
  102.                                 $this->allowExts = array_map('strtolower',$allowExts);
  103.                         }else {
  104.                                 $this->allowExts = explode(',',strtolower($allowExts));
  105.                         }
  106.                 }
  107.                 if(!empty($allowTypes)) {
  108.                         if(is_array($allowTypes)) {
  109.                                 $this->allowTypes = array_map('strtolower',$allowTypes);
  110.                         }else {
  111.                                 $this->allowTypes = explode(',',strtolower($allowTypes));
  112.                         }
  113.                 }
  114.                 if(!empty($savePath)) {
  115.                         $this->savePath = $savePath;
  116.                 }
  117.                 if(!empty($saveRule)) {
  118.                         $this->saveRule = $saveRule;
  119.                 }
  120.  
  121.  
  122.         }
  123.  
  124.         private function save($file)
  125.         {
  126.                 $filename = $file['savepath'].$file['savename'];
  127.                 if(!$this->uploadReplace && is_file($filename)) {
  128.                         // 不覆盖同名文件
  129.                         $this->error    =       '文件已经存在!'.$filename;
  130.                         return false;
  131.                 }
  132.                 // 如果是图像文件 检测文件格式
  133.                 if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf')) && false === getimagesize($file['tmp_name'])) {
  134.                         $this->error = '非法图像文件';
  135.                         return false;
  136.                 }
  137.                 if(!move_uploaded_file($file['tmp_name'], iconv('utf-8','gbk',$filename))) {
  138.                         $this->error = '文件上传保存错误!';
  139.                         return false;
  140.                 }
  141.                 if($this->thumb && in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png'))) {
  142.                         $image =  getimagesize($filename);
  143.                         if(false !== $image) {
  144.                                 //是图像文件生成缩略图
  145.                                 $thumbWidth             =       explode(',',$this->thumbMaxWidth);
  146.                                 $thumbHeight            =       explode(',',$this->thumbMaxHeight);
  147.                                 $thumbPrefix            =       explode(',',$this->thumbPrefix);
  148.                                 $thumbSuffix = explode(',',$this->thumbSuffix);
  149.                                 $thumbFile                      =       explode(',',$this->thumbFile);
  150.                                 $thumbPath    =  $this->thumbPath?$this->thumbPath:$file['savepath'];
  151.                                 // 生成图像缩略图
  152.                                 if(file_exists(dirname(__FILE__).'/Image.class.php'))
  153.                                 {
  154.                                         require_once(dirname(__FILE__).'/Image.class.php');
  155.                                         $realFilename  =  $this->autoSub?basename($file['savename']):$file['savename'];
  156.                                         for($i=0,$len=count($thumbWidth); $i<$len; $i++) {
  157.                                                 $thumbname      =       $thumbPath.$thumbPrefix[$i].substr($realFilename,0,strrpos($realFilename, '.')).$thumbSuffix[$i].'.'.$file['extension'];
  158.                                                 Image::thumb($filename,$thumbname,'',$thumbWidth[$i],$thumbHeight[$i],true);
  159.                                         }
  160.                                         if($this->thumbRemoveOrigin) {
  161.                                                 // 生成缩略图之后删除原图
  162.                                                 unlink($filename);
  163.                                         }
  164.                                 }
  165.                         }
  166.                 }
  167.                 if($this->zipImags) {
  168.                         // TODO 对图片压缩包在线解压
  169.  
  170.                 }
  171.                 return true;
  172.         }
  173.  
  174.         /**
  175.          +----------------------------------------------------------
  176.          * 上传文件
  177.          +----------------------------------------------------------
  178.          * @access public
  179.          +----------------------------------------------------------
  180.          * @param string $savePath  上传文件保存路径
  181.          +----------------------------------------------------------
  182.          * @return string
  183.          +----------------------------------------------------------
  184.          * @throws ThinkExecption
  185.          +----------------------------------------------------------
  186.          */
  187.         public function upload($savePath ='')
  188.         {
  189.                 //如果不指定保存文件名,则由系统默认
  190.                 if(empty($savePath))
  191.                 $savePath = $this->savePath;
  192.                 // 检查上传目录
  193.                 if(!is_dir($savePath)) {
  194.                         // 检查目录是否编码后的
  195.                         if(is_dir(base64_decode($savePath))) {
  196.                                 $savePath       =       base64_decode($savePath);
  197.                         }else{
  198.                                 // 尝试创建目录
  199.                                 if(!mkdir($savePath)){
  200.                                         $this->error  =  '上传目录'.$savePath.'不存在';
  201.                                         return false;
  202.                                 }
  203.                         }
  204.                 }else {
  205.                         if(!is_writeable($savePath)) {
  206.                                 $this->error  =  '上传目录'.$savePath.'不可写';
  207.                                 return false;
  208.                         }
  209.                 }
  210.                 $fileInfo = array();
  211.                 $isUpload   = false;
  212.  
  213.                 // 获取上传的文件信息
  214.                 // 对$_FILES数组信息处理
  215.                 $files   =       $this->dealFiles($_FILES);
  216.                 foreach($files as $key => $file) {
  217.                         //过滤无效的上传
  218.                         if(!empty($file['name'])) {
  219.                                 //登记上传文件的扩展信息
  220.                                 $file['key']          =  $key;
  221.                                 $file['extension']  = $this->getExt($file['name']);
  222.                                 $file['savepath']   = $savePath;
  223.                                 $file['savename']   = $this->getSaveName($file);
  224.  
  225.                                 // 自动检查附件
  226.                                 if($this->autoCheck) {
  227.                                         if(!$this->check($file))
  228.                                         return false;
  229.                                 }
  230.  
  231.                                 //保存上传文件
  232.                                 if(!$this->save($file)) return false;
  233.                                 /*
  234.                                  if(function_exists($this->hashType)) {
  235.                                  $fun =  $this->hashType;
  236.                                  $file['hash']   =  $fun(auto_charset($file['savepath'].$file['savename'],'utf-8','gbk'));
  237.                                  }
  238.                                  */
  239.                                 //上传成功后保存文件信息,供其他地方调用
  240.                                 unset($file['tmp_name'],$file['error']);
  241.                                 $fileInfo[] = $file;
  242.                                 $isUpload   = true;
  243.                         }
  244.                 }
  245.                 if($isUpload) {
  246.                         $this->uploadFileInfo = $fileInfo;
  247.                         return true;
  248.                 }else {
  249.                         $this->error  =  '没有选择上传文件';
  250.                         return false;
  251.                 }
  252.         }
  253.  
  254.         /**
  255.          +----------------------------------------------------------
  256.          * 转换上传文件数组变量为正确的方式
  257.          +----------------------------------------------------------
  258.          * @access private
  259.          +----------------------------------------------------------
  260.          * @param array $files  上传的文件变量
  261.          +----------------------------------------------------------
  262.          * @return array
  263.          +----------------------------------------------------------
  264.          */
  265.         private function dealFiles($files) {
  266.                 $fileArray = array();
  267.                 foreach ($files as $file){
  268.                         if(is_array($file['name'])) {
  269.                                 $keys = array_keys($file);
  270.                                 $count   =       count($file['name']);
  271.                                 for ($i=0; $i<$count; $i++) {
  272.                                         foreach ($keys as $key)
  273.                                         $fileArray[$i][$key] = $file[$key][$i];
  274.                                 }
  275.                         }else{
  276.                                 $fileArray      =       $files;
  277.                         }
  278.                         break;
  279.                 }
  280.                 return $fileArray;
  281.         }
  282.  
  283.         /**
  284.          +----------------------------------------------------------
  285.          * 获取错误代码信息
  286.          +----------------------------------------------------------
  287.          * @access public
  288.          +----------------------------------------------------------
  289.          * @param string $errorNo  错误号码
  290.          +----------------------------------------------------------
  291.          * @return void
  292.          +----------------------------------------------------------
  293.          * @throws ThinkExecption
  294.          +----------------------------------------------------------
  295.          */
  296.         protected function error($errorNo)
  297.         {
  298.                 switch($errorNo) {
  299.                         case 1:
  300.                                 $this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
  301.                                 break;
  302.                         case 2:
  303.                                 $this->error = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
  304.                                 break;
  305.                         case 3:
  306.                                 $this->error = '文件只有部分被上传';
  307.                                 break;
  308.                         case 4:
  309.                                 $this->error = '没有文件被上传';
  310.                                 break;
  311.                         case 6:
  312.                                 $this->error = '找不到临时文件夹';
  313.                                 break;
  314.                         case 7:
  315.                                 $this->error = '文件写入失败';
  316.                                 break;
  317.                         default:
  318.                                 $this->error = '未知上传错误!';
  319.                 }
  320.                 return ;
  321.         }
  322.  
  323.         /**
  324.          +----------------------------------------------------------
  325.          * 根据上传文件命名规则取得保存文件名
  326.          +----------------------------------------------------------
  327.          * @access private
  328.          +----------------------------------------------------------
  329.          * @param string $filename 数据
  330.          +----------------------------------------------------------
  331.          * @return string
  332.          +----------------------------------------------------------
  333.          */
  334.         private function getSaveName($filename)
  335.         {
  336.                 $rule = $this->saveRule;
  337.                 if(empty($rule)) {//没有定义命名规则,则保持文件名不变
  338.                         $saveName = $filename['name'];
  339.                 }else {
  340.                         if(function_exists($rule)) {
  341.                                 //使用函数生成一个唯一文件标识号
  342.                                 $saveName = $rule().".".$filename['extension'];
  343.                         }else {
  344.                                 //使用给定的文件名作为标识号
  345.                                 $saveName = $rule.".".$filename['extension'];
  346.                         }
  347.                 }
  348.                 if($this->autoSub) {
  349.                         // 使用子目录保存文件
  350.                         $saveName   =  $this->getSubName($filename).'/'.$saveName;
  351.                 }
  352.                 return $saveName;
  353.         }
  354.  
  355.         /**
  356.          +----------------------------------------------------------
  357.          * 获取子目录的名称
  358.          +----------------------------------------------------------
  359.          * @access private
  360.          +----------------------------------------------------------
  361.          * @param array $file  上传的文件信息
  362.          +----------------------------------------------------------
  363.          * @return string
  364.          +----------------------------------------------------------
  365.          */
  366.         private function getSubName($file)
  367.         {
  368.                 switch($this->subType) {
  369.                         case 'date':
  370.                                 $dir   =  date($this->dateFormat,time());
  371.                                 break;
  372.                         case 'hash':
  373.                         default:
  374.                                 $name = md5($file['savename']);
  375.                                 $dir   =  '';
  376.                                 for($i=0;$i<$this->hashLevel;$i++) {
  377.                                         $dir   .=  $name{0}.'/';
  378.                                 }
  379.                                 break;
  380.                 }
  381.                 if(!is_dir($file['savepath'].$dir)) {
  382.                         mkdir($file['savepath'].$dir);
  383.                 }
  384.                 return $dir;
  385.         }
  386.  
  387.         /**
  388.          +----------------------------------------------------------
  389.          * 检查上传的文件
  390.          +----------------------------------------------------------
  391.          * @access private
  392.          +----------------------------------------------------------
  393.          * @param array $file 文件信息
  394.          +----------------------------------------------------------
  395.          * @return boolean
  396.          +----------------------------------------------------------
  397.          */
  398.         private function check($file) {
  399.                 if($file['error']!== 0) {
  400.                         //文件上传失败
  401.                         //捕获错误代码
  402.                         $this->error($file['error']);
  403.                         return false;
  404.                 }
  405.  
  406.                 //检查文件Mime类型
  407.                 if(!$this->checkType($file['type'])) {
  408.                         $this->error = '上传文件MIME类型不允许!';
  409.                         return false;
  410.                 }
  411.                 //检查文件类型
  412.                 if(!$this->checkExt($file['extension'])) {
  413.                         $this->error ='上传文件类型不允许';
  414.                         return false;
  415.                 }
  416.                 //文件上传成功,进行自定义规则检查
  417.                 //检查文件大小
  418.                 if(!$this->checkSize($file['size'])) {
  419.                         $this->error = '上传文件大小超出限制!';
  420.                         return false;
  421.                 }
  422.  
  423.                 //检查是否合法上传
  424.                 if(!$this->checkUpload($file['tmp_name'])) {
  425.                         $this->error = '非法上传文件!';
  426.                         return false;
  427.                 }
  428.                 return true;
  429.         }
  430.  
  431.         /**
  432.          +----------------------------------------------------------
  433.          * 检查上传的文件类型是否合法
  434.          +----------------------------------------------------------
  435.          * @access private
  436.          +----------------------------------------------------------
  437.          * @param string $type 数据
  438.          +----------------------------------------------------------
  439.          * @return boolean
  440.          +----------------------------------------------------------
  441.          */
  442.         private function checkType($type)
  443.         {
  444.                 if(!empty($this->allowTypes))
  445.                 return in_array(strtolower($type),$this->allowTypes);
  446.                 return true;
  447.         }
  448.  
  449.  
  450.         /**
  451.          +----------------------------------------------------------
  452.          * 检查上传的文件后缀是否合法
  453.          +----------------------------------------------------------
  454.          * @access private
  455.          +----------------------------------------------------------
  456.          * @param string $ext 后缀名
  457.          +----------------------------------------------------------
  458.          * @return boolean
  459.          +----------------------------------------------------------
  460.          */
  461.         private function checkExt($ext)
  462.         {
  463.                 if(!empty($this->allowExts))
  464.                 return in_array(strtolower($ext),$this->allowExts,true);
  465.                 return true;
  466.         }
  467.  
  468.         /**
  469.          +----------------------------------------------------------
  470.          * 检查文件大小是否合法
  471.          +----------------------------------------------------------
  472.          * @access private
  473.          +----------------------------------------------------------
  474.          * @param integer $size 数据
  475.          +----------------------------------------------------------
  476.          * @return boolean
  477.          +----------------------------------------------------------
  478.          */
  479.         private function checkSize($size)
  480.         {
  481.                 return !($size > $this->maxSize) || (-1 == $this->maxSize);
  482.         }
  483.  
  484.         /**
  485.          +----------------------------------------------------------
  486.          * 检查文件是否非法提交
  487.          +----------------------------------------------------------
  488.          * @access private
  489.          +----------------------------------------------------------
  490.          * @param string $filename 文件名
  491.          +----------------------------------------------------------
  492.          * @return boolean
  493.          +----------------------------------------------------------
  494.          */
  495.         private function checkUpload($filename)
  496.         {
  497.                 return is_uploaded_file($filename);
  498.         }
  499.  
  500.         /**
  501.          +----------------------------------------------------------
  502.          * 取得上传文件的后缀
  503.          +----------------------------------------------------------
  504.          * @access private
  505.          +----------------------------------------------------------
  506.          * @param string $filename 文件名
  507.          +----------------------------------------------------------
  508.          * @return boolean
  509.          +----------------------------------------------------------
  510.          */
  511.         private function getExt($filename)
  512.         {
  513.                 $pathinfo = pathinfo($filename);
  514.                 return $pathinfo['extension'];
  515.         }
  516.  
  517.         /**
  518.          +----------------------------------------------------------
  519.          * 取得上传文件的信息
  520.          +----------------------------------------------------------
  521.          * @access public
  522.          +----------------------------------------------------------
  523.          * @return array
  524.          +----------------------------------------------------------
  525.          */
  526.         public function getUploadFileInfo()
  527.         {
  528.                 return $this->uploadFileInfo;
  529.         }
  530.  
  531.         /**
  532.          +----------------------------------------------------------
  533.          * 取得最后一次错误信息
  534.          +----------------------------------------------------------
  535.          * @access public
  536.          +----------------------------------------------------------
  537.          * @return string
  538.          +----------------------------------------------------------
  539.          */
  540.         public function getErrorMsg()
  541.         {
  542.                 return $this->error;
  543.         }
  544.  
  545. }//类定义结束
  546. ?>

回复 "php文件和图片上传类"

这儿你可以回复上面这条便签

captcha