Home >Backend Development >PHP Tutorial >thinkphp file upload class

thinkphp file upload class

WBOY
WBOYOriginal
2016-08-08 09:31:411055browse

/**
*This is a file upload class, used to process uploaded files, pictures, etc., and can automatically generate thumbnails and add watermarks
*/
// +--------------------------------- ----------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +------------------------------------------------ --------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +- -------------------------------------------------- ------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----- -------------------------------------------------- ---------------
// | Author: hxsml
// +------------------------ --------------------------------------------------
// $ Id: UploadFile.class.php v1.0
/**
+------------------------------------------------ ----------------------------------
* File upload class
*
* Modification:
* When uploading multiple files, fileinfo will be Array with form name as key
+--------------------------------------------- ------------------------------------
* @category ORG
* @package ORG
* @subpackage Net
* @author hxsml
* @version v1.0
+----------------------------------- --------------------------------------------------
*/
class UploadFile {//Start of class definition
// Maximum size of uploaded files
Public $maxSize = -1;
// Whether to support multiple File upload
public $supportMulti = true;
// File suffixes allowed to be uploaded
// Leave blank without suffix checking
public $allowExts = array();
// File types allowed to be uploaded
// Leave blank without checking
public $allowTypes = array();
// Use thumbnail processing for uploaded images
public $thumb = false;
// Gallery class package path
public $imageClassPath = 'ORG.Util.Image';
// Thumbnail maximum width
public $thumbMaxWidth;
// Maximum thumbnail height
public $thumbMaxHeight;
// Thumbnail prefix
public $thumbPrefix = 'thumb_';
public $thumbSuffix = '';
// Thumbnail save Path
public $thumbPath = '';
// Thumbnail file name
public $thumbFile='';
// Whether to remove the original image
public $thumbRemoveOrigin = false;
// Upload compressed image file
public $zipImages = false;
// Enable saving files in subdirectories
public $autoSub = false;
// You can use hash date to create subdirectories
public $subType = 'hash';
public $dateFormat = 'Ymd' ;
public $hashLevel = 1; // Directory level of hash
// Upload file saving path
public $savePath = '';
public $autoCheck = true; // Whether to automatically check attachments
// Whether to overwrite files with the same name
public $uploadReplace = false;
// Upload file naming rules
// For example, it can be time uniqid com_create_guid, etc.
// It must be a function name without any parameters. You can use a custom function
public $saveRule = '';
// Upload file Hash rule function name
// For example, it can be md5_file sha1_file, etc.
public $hashType = 'md5_file';
// Error message
private $error = '';
// File information of successful upload
private $uploadFileInfo ;
/**
+------------------------------------------------ ----------
* Architectural function
+---------------------------------- --------------------------
* @access public
+------------------- ---------------------------------------
*/
public function __construct($maxSize='',$allowExts='',$allowTypes='',$savePath='',$saveRule='') {
if (!empty($maxSize) && is_numeric($maxSize)) {
                                                          use using using ’s ’ s ’ s to use ’s ’ s             ‐ ‐ ‐‐‐‐‐                                                              
$this->allowExts = array_map('strtolower',$allowExts);
        }else {
                $this->allowExts = explode(',',strtolower($allowExts));
            }
        }
        if(!empty($allowTypes)) {
            if(is_array($allowTypes)) {
                $this->allowTypes = array_map('strtolower',$allowTypes);
            }else {
                $this->allowTypes = explode(',',strtolower($allowTypes));
            }
        }
        if(!empty($saveRule)) {
            $this->saveRule = $saveRule;
        }else{
            $this->saveRule=C('UPLOAD_FILE_RULE');
        }
        $this->savePath = $savePath;
    }
    /**
+------------------------------------------------ ----------
* Upload a file
+---------------------------------- --------------------------
* @access public
+------------------ ----------------------------------------
* @param mixed $name data
* @param string $value Data table name
+---------------------------------------- ------------------
* @return string
+------------------------- ----------------------------------
* @throws ThinkExecption
+---------- ------------------------------------------------
*/
    private function save($file) {
        $filename = $file['savepath'].$file['savename'];
        if(!$this->uploadReplace && is_file($filename)) {
            // 不覆盖同名文件
            $this->error='文件已经存在!'.$filename;
            return false;
        }
        // 如果是图像文件 检测文件格式
        if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf')) && false === getimagesize($file['tmp_name'])) {
            $this->error = '非法图像文件';
            return false;
        }
        if(!move_uploaded_file($file['tmp_name'], $this->auto_charset($filename,'utf-8','gbk'))) {
            $this->error = '文件上传保存错误!';
            return false;
        }
        if($this->thumb && in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png'))) {
            $image =  getimagesize($filename);
            if(false !== $image) {
                //是图像文件生成缩略图
                $thumbWidth=explode(',',$this->thumbMaxWidth);
                $thumbHeight=explode(',',$this->thumbMaxHeight);
                $thumbPrefix=explode(',',$this->thumbPrefix);
                $thumbSuffix = explode(',',$this->thumbSuffix);
                $thumbFile=explode(',',$this->thumbFile);
                $thumbPath    =  $this->thumbPath?$this->thumbPath:$file['savepath'];
                // 生成图像缩略图
                import($this->imageClassPath);
                $realFilename  =  $this->autoSub?basename($file['savename']):$file['savename'];
                for($i=0,$len=count($thumbWidth); $i<$len; $i++) {
                    $thumbname=$thumbPath.$thumbPrefix[$i].substr($realFilename,0,strrpos($realFilename, '.')).$thumbSuffix[$i].'.'.$file['extension'];
                    Image::thumb($filename,$thumbname,'',$thumbWidth[$i],$thumbHeight[$i],true);
                }
                if($this->thumbRemoveOrigin) {
                    // 生成缩略图之后删除原图
                    unlink($filename);
                }
            }
        }
        if($this->zipImags) {
            // TODO 对图片压缩包在线解压
        }
        return true;
    }
    /**
+------------------------------------------------ ----------
* Upload all files
+---------------------------------- --------------------------
* @access public
+------------------ ----------------------------------------
* @param string $savePath Upload file to save Path
+-------------------------------------------------- ----------
* @return string
+-------------------------------- --------------------------
* @throws ThinkExecption
+----------------- ----------------------------------------
*/
    public function upload($savePath ='') {
        //如果不指定保存文件名,则由系统默认
        if(empty($savePath))
            $savePath = $this->savePath;
        // 检查上传目录
        if(!is_dir($savePath)) {
            // 检查目录是否编码后的
            if(is_dir(base64_decode($savePath))) {
                $savePath=base64_decode($savePath);
            }else{
                // 尝试创建目录
                if(!mkdir($savePath)){
                    $this->error  =  '上传目录'.$savePath.'不存在';
                    return false;
                }
            }
        }Else {(if (! IS_WRITEable ($ savepath)) {
$ this- & gt; error = 'Upload directory'. $ savepath. ay (); L $ isupload = false;
// Get the uploaded file information
// For the $ _Files array information processing
$ Files

=

$ This- & GT; Dealfiles ($ _ Files); => $file) {
                                                                                                                                                                                           ‐ $key ;
                                                                                                                                       >getSaveName($file);                        return false; Upload file                                                                                                if(!$this->save($file)) return false;                       $file[' hash'] = $fun($this->auto_charset($file['savepath'].$file['savename'],'utf-8','gbk'));                                                                                                                                                         Save file information for other places to call unset ($ file ['tmp_name'], $ file ['error']); $ FileInfo [$ Key] = $ file; if($isUpload) {
                                                                     $this-> ;
                return false;
        }
}
/**
+------------------------------------------------ ----------
* Uploading files in a single upload field supports multiple attachments
+-------------------------- --------------------------------
* @access public
+----------- --------------------------------------------------
* @ param array $file Upload file information
* @param string $savePath Upload file save path
+--------------------------------- ----------------------------
* @return string
+--------------- ------------------------------------------
* @throws ThinkExecption
+ -------------------------------------------------- --------
*/
public function uploadOne($file,$savePath=''){
                                                            using using using            out out through ’’ ’s' ’ through ’ s through through through through through‐ through ‐‐ ‐‐‐‐‐‐ and
_ to = $this->savePath;
                                                                                                                                          $this->error = 'Upload the directory'. $ Savepath. 'No';
Return false;
}} else {
if (! Is_writeable ($ savepath)) {
$ this- & gt; upload directory '. PATH. 'Not writable';                          return false; ;
                                                           file ['name'])) {
$ keys = array_keys ($ file);
$ count

=

Count ($ file ['name']);
for ($ i = 0; $ i & lt; $ count; $i++) {
                                                                                                                                               }else{
                  $fileArray[] = $ file; $file['extension'] = $this-> ;getExt($file['name']); H if ($ this-& gt; autocheck) {
if (! $ This-& gt; check ($ file))
Return false; file)) return false; $this->auto_charset( $file['savepath'].$file['savename'],'utf-8','gbk'));
            }(Unset ($ File ['tmp_name'], $ file ['error']);
$ info [] = $ file;
}
// Return the uploaded file information
Return $ info; this->error = 'No file uploaded';
Return false;
}
}
// Automatic conversion of character set supports array conversion
private function auto_charset($fContents, $from='gbk', $to=' utf-8') {
          $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
            $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
                                                                                                                                                                                                                                             ​If (is_string($fContents)) {
if (function_exists('mb_convert_en')) {
}
if (is_string($fContents)) {
return mb_convert_encoding($fContents, $to, $from) ;
                                                                                                                                                                                              } }
    } elseif (is_array($fContents)) {
foreach ($fContents as $key => $val) {
                                                                                            using           using   using  -                                  $val, $from, $to);
                                                                                                                                                             } }
        else {
              return $fContents;
        }
}

/**
+------------------------------------------------ ----------
* Convert the upload file array variable to the correct way
* *
* Modification:
* When setting name=upload[], the key is "upload", corresponding to a file containing multiple files
* * Multi-dimensional array indexed by numeric index, name=upload1..., key is the name corresponding to
* +--------------------- ----------------------------------------
* @access private
+------ -------------------------------------------------- --
* @param array $files Uploaded file variables
+----------------------------------- -----------------------
* @return array
+-------------------------- ----------------------------------------
*/
private function dealFiles($files) {
  $fileArray = array();
    foreach ($files as $field => $file){
                                         file ['name'])) {
$ keys = array_keys ($ file);
$ count

=

Count ($ file ['name']);
for ($ i = 0; $ i & lt; $ count; $i++) {
                                                                                                                                         }else{
                $fileArray[$field |
/**
+------------------------------------------------ ----------
* Get error code information
+-------------------------------- --------------------------
* @access public
+----------------- --------------------------------------------------
* @param string $errorNo Error number
+------------------------------------------------ ----------
* @return void
+---------------------------------- --------------------------
* @throws ThinkExecption
+------------------ ----------------------------------------
*/
protected function error($errorNo) {
switch($errorNo) {
case 1:
$this->error = 'The uploaded file exceeds the upload_max_filesize option limit in php.ini The value '; a Break;
case 2:
$ this-& gt; error =' The size of the upload file exceeds the value specified by the max_file_size option in the html form '; = 'Only part of the file was uploaded'; :
                  $this->error = 'Not found Temporary folder';
                  break;​ ​ ​ ​ ​ $this->error = 'Unknown upload error!';
                                                                                                                                                                                     . ($rule)) {//If no naming rules are defined, the file name will remain unchanged
       //$saveName = $filename['name'];


$saveName = date('YmdHis').rand().".".$ filename['extension'];
    }else{



                                                                                                                                                                                                                 . ".$filename ['extension'];
                                                                                                                                                                                           
           }
                                                                                                                   ->autoSub) {
                                                                                                                                                                                                                                                                                       $filename)
                                       return $saveName; dir = date($this ->dateFormat,time());                                 break;                                                    0;$i<$this->hashLevel;$i++) {
                                                                }
If(!is_dir($file['savepath '].$dir)) {                   mk_dir($file['savepath'].$dir);                                                                                                    
/**
+------------------------------------------------ ----------
* Check uploaded files
+-------------------------------- --------------------------
* @access private
+----------------- --------------------------------------------------
* @param array $file file information
+------------------------------------------------ ----------
* @return boolean
+---------------------------------- ------------------------
*/
private function check($file) {
                                                                                                                        using ‐ ’ ’ s
                 ’ ‐ ’ ’ s ‐ ‐ ‐ ‐ ‐ ‐ ,                                                                                 to >error($file['error']); ['size'])) {
$ this- & gt; error = 'Upload file size is not consistent! ';
                return false; allow! ';
Return false;
}
// Check the file type
if (! $ This- & gt; checkext ($ file [' extension ']) {
$ this- & gt; error =' Upload file type is not allowed ' ; U Return false;
}
// Check whether it is legally uploaded












($ file ['tmp_name']) {
$ This- & gt; error = 'illegal upload file!';
            return false;
        }
        return true;
    }
    /**
+------------------------------------------------ ----------
* Check whether the uploaded file type is legal
+----------------------------- --------------------------
* @access private
+-------------- --------------------------------------------------
* @param string $ type data
+------------------------------------------------ ------------
* @return boolean
+---------------------------------- --------------------------
*/
    private function checkType($type) {
        if(!empty($this->allowTypes))
            return in_array(strtolower($type),$this->allowTypes);
        return true;
    }
    /**
+------------------------------------------------ ----------
* Check whether the uploaded file suffix is ​​legal
+----------------------------- --------------------------
* @access private
+-------------- --------------------------------------------------
* @param string $ ext suffix
+------------------------------------------------ -------------
* @return boolean
+--------------------------------- ----------------------------
*/
    private function checkExt($ext) {
        if(!empty($this->allowExts))
            return in_array(strtolower($ext),$this->allowExts,true);
        return true;
    }
    /**
+------------------------------------------------ ----------
* Check whether the file size is legal
+---------------------------------- --------------------------
* @access private
+---------------- ------------------------------------------------
* @param integer $size data
+------------------------------------------------ ----------
* @return boolean
+---------------------------------- ------------------------
*/
    private function checkSize($size) {
        return !($size > $this->maxSize) || (-1 == $this->maxSize);
    }
    /**
+------------------------------------------------ ----------
* Check whether the file was submitted illegally
+---------------------------------- --------------------------
* @access private
+---------------- ------------------------------------------
* @param string $filename file Name
+------------------------------------------------------------- ----------
* @return boolean
+-------------------------------- --------------------------
*/
    private function checkUpload($filename) {
        return is_uploaded_file($filename);
    }
    /**
+------------------------------------------------ ----------
* Get the suffix of the uploaded file
+---------------------------------- --------------------------
* @access private
+---------------- ------------------------------------------
* @param string $filename file Name
+------------------------------------------------------------- ----------
* @return boolean
+-------------------------------- --------------------------
*/
    private function getExt($filename) {
        $pathinfo = pathinfo($filename);
        return $pathinfo['extension'];
    }
/**
+------------------------------------------------ ----------
* Get uploaded file information
+---------------------------------- --------------------------
* @access public
+---------------- ------------------------------------------
* @return array
+- -------------------------------------------------- -------
*/
public function getUploadFileInfo() {
return $this->uploadFileInfo;
}
/**
+------------------------------------------------ ----------
* Get the last error message
+---------------------------------- --------------------------
* @access public
+---------------- ------------------------------------------
* @return string
+- -------------------------------------------------- -------
*/
public function getErrorMsg() {
return $this-> error;
}
}

The above introduces the thinkphp file upload class, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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