search
HomeBackend DevelopmentPHP Tutorialthinkphp file upload class

/**
*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                    $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;$ihashLevel;$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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)