Home Backend Development PHP Tutorial thinkphp file upload class

thinkphp file upload class

Aug 08, 2016 am 09:31 AM
file nbsp return this

/**
*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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

OOBELANGUAGE Error Problems in Windows 11/10 Repair OOBELANGUAGE Error Problems in Windows 11/10 Repair Jul 16, 2023 pm 03:29 PM

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

How to Fix Activation Error Code 0xc004f069 in Windows Server How to Fix Activation Error Code 0xc004f069 in Windows Server Jul 22, 2023 am 09:49 AM

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using

See all articles