文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>[代码] 文件上传类

[代码] 文件上传类

时间:2008-08-18  来源:liuxingyuyuni

文件上传类

[未经严格测试,需要的可以拿去使用,不负任何责任.]



?php
    /**
     * @auther        Bian Yuan
     * @email        [email protected]
     * @date     Sun Aug 17 19:15:21 GMT 2008
     *
     * @copyright (c) 2008 - Bian Yuan Free to use, distribute, and modify.
     *
     * @desc         File Upload
     * @version     0.1
     * @example
     *====================================================================================
     *         $objUpload = new FileUpload('./upload', array('gif','png','jpg','jpeg'));
     *        $objUpload->upfile('file');
     *        echo "File upload info";
     *        print_r($objUpload->getUploadInfo());
     *        echo "
";
     *        echo "Upload error info";
     *        print_r($objUpload->getErrorInfo());
     *=====================================================================================
     * @history
     *
    */
    define('UPLOAD_MAX_FILE_SIZE_ERROR', 'File size too large.');
    define('UPLOAD_INVALID_FILE_EXT', 'File extension not permitted.');
    define('UPLOAD_NO_FILE_SELECT', 'You haven not selected any file to upload');
    define('UPLOAD_DIRECTORY_NOT_WRITABLE', 'The upload directory doesn\'t have write perms.');
    define('UPLOAD_FILE_EXISTS_ERROR', 'The destination file already exists.');
    define('UPLOAD_FILEUPLOAD_FAILED', 'File upload failed');
   
    class FileUpload {
        private $file = null;
        private $uploadPath = null;
        private $allowType = array('gif', 'png', 'jpg', 'jpeg');
        private $maxSize = 2048000;
        private $overwrite     = true;
        private $errorInfo = array();
        private $fileInfo = array();
        private $numFiles = 0;
        /**
         * @desc    Constructor function
         * @param     String     $overwrite
         * @param     Array     $allowType
         * @param     Integer    $maxSize
         * @access     public
         * @return     None
         * */
        public function FileUpload($uploadPath='', $allowType=array(), $overwrite=true, $maxSize=2048000) {
            $this->uploadPath = realpath($uploadPath);
            $this->allowType = (array)$allowType;
            $this->overwrite = (boolean)$overwrite;
            $this->maxSize = (int)$maxSize;
        }
        /**
         *
         * Upload file
         *
         * @param         String $file
         * @access     Public
         * @return     Boolean upload succeed or failed
         * */
        public function upfile($file) {
            $this->numFiles = count($_FILES[$file]['name']);
            if(1 == $this->numFiles) {
                @extract($_FILES[$file], EXTR_OVERWRITE);
                $_FILES = array();
                $_FILES[$file]['name'][0] = $name;
                $_FILES[$file]['type'][0] = $type;
                $_FILES[$file]['tmp_name'][0] = $tmp_name;
                $_FILES[$file]['size'][0] = $size;
                $_FILES[$file]['error'][0] = $error;
                unset($name, $type, $tmp_name, $size, $error);
            }
            for($i=0; $i$this->numFiles; $i++) {
                $this->doCheck($_FILES[$file]);
                if(! empty($this->errorInfo)) {
                    return false;
                }
                $ext = $this->getFileExtension($_FILES[$file]['name'][$i]);
                $name = $this->getRandName();
                $this->fileInfo[$i] = array(
                    'name' => basename($_FILES[$file]['name'][$i]),
                    'rand_name' => basename($name . '.' . $ext),
                    'ext' => $ext,
                    'size' => intval($_FILES[$file]['size'][$i]),
                    'tmp' => $_FILES[$file]['tmp_name'][$i],
                );
                if(! $this->doUpfileDetail($this->fileInfo[$i]['tmp'], $this->fileInfo[$i]['rand_name'])) {
                    return false;
                }
            }
            return true;
        }
        /**
         *
         * Upload file detail
         *
         * @param         String $file
         * @param         String $destination
         * @access     Private
         * @return     Boolean upload file succeed or failed
         * */
        private function doUpfileDetail($file, $destName) {
            $distFile = $this->uploadPath . '/' . $destName;
            if(file_exists($distFile)) {
                if($this->overwrite) {
                    @unlink($distFile);
                }else{
                    $this->errorInfo['fileExists'] = UPLOAD_FILE_EXISTS_ERROR;
                    return false;
                }
            }
            if(is_uploaded_file($file)) {
                if(! @move_uploaded_file($file, $distFile)) {
                    $this->errorInfo['uploadFailed'] = UPLOAD_FILEUPLOAD_FAILED;
                    return false;
                }
                @chmod($distFile, 0755);
            }
            return true;
        }
        /**
         *
         * Check for a valid upload file
         *
         * @param         Array $fileInfo
         * @access     Private
         * @return     Booean file is valid or not
         */
        private function doCheck($fileInfo) {            
            for($i=0; $i$this->numFiles; $i++) {
                $errno = (int)$fileInfo['error'][$i];
                if(1 == $errno || !$this->isValidFilesize($fileInfo['size'][$i])) {
                    $this->errorInfo[$i]['maxSize'] = UPLOAD_MAX_FILE_SIZE_ERROR;
                }
                if(4 == $errno || '' == $fileInfo['name'][$i]) {
                    $this->errorInfo[$i]['name'] = UPLOAD_NO_FILE_SELECT;
                }            
                $ext = $this->getFileExtension($fileInfo['name'][$i]);
                if(! $this->isValidExtension($ext)) {
                    $this->errorInfo[$i]['ext'] = UPLOAD_INVALID_FILE_EXT;
                }
            }
            return true;
        }
        /**
         *
         * Set upload file path
         *
         * @param         String $dir
         * @access     Public
         * @return     Void
         * */
        public function setUploadDir($dir) {
            if(! is_writable($dir)){
                $this->errorInfo['dir'] = UPLOAD_FILE_NOT_WRITABLE;
            }else{
                $this->upload_path = realpath($dir);   
            }
        }
        /**
         *
         * Set max file size allow to upload
         *
         * @param         Integer $size b
         * @access     Public
         * @return     Void
         * */
        public function setMaxFileSize($size) {
            $this->max_size = (int) $size;
        }
        /**
         *
         * Set is overwrite mode when file is exists
         *     
         * @param         Boolean $mode
         * @access     Public
         * @return     Void
         * */
        public function setOverWriteMode($mode=true) {
            $this->overwrite = (bool) $mode;
        }
        /**
         * Set which extension allow to upload
         *
         * @param         Array $ext
         * @access     Public
         * @return     Void
         */
        public function setValidExtension($ext = array()) {
            $this->allowType = (array)$ext;
        }
        /**
         *
         * Get random String
         *
         * @param         String $len
         * @access     Private
         * @return     String
         * */
        private function getRandName($len=25) {
            $randname = date('YmdHis').rand(1,10000);
            return substr($randname,0,$len);
        }
        /**
         *
         * Get upload file ext string
         *
         * @param         String $filename
         * @access     Private
         * @return     String
         * */
        private function getFileExtension($filename) {
            if(@$ps = strrpos($filename , '.')) {
                return strtolower(substr($filename, $ps+1));
            }
        }
        /**
         *
         * Get Upload info
         *
         * @param         Void
         * @access     Public
         * @return     Array upload info
         */
        public function getUploadInfo() {
            return $this->fileInfo;
        }
        /**
         *
         * Get formated size from file
         *
         * @param         Integer $size;
         * @param         String    $format b|kb|mb
         * @access     Private
         * @return     Integer
         * */
        private function formatFileSize($size, $format='kb') {
            switch (strtolower($format)) {
                case 'b':
                    $formatSize = $size;
                    break;
                case 'kb':
                    $formatSize = floor($size/1024);
                    break;
                case 'mb':
                    $formatSize = floor($size/(1024*1024));
                    break;
                default:
                    $formatSize = $size;
            }
            return $formatSize;
        }
        /**
         *
         * Check file extionsion
         *
         * @param         String $ext
         * @access     Private
         * @return     Boolean
         * */
        private function isValidExtension($ext) {
            if(! in_array($ext, $this->allowType)) {
                return false;
            }
            return true;
        }
        /**
         *
         * Check file size
         *
         * @param         $filesize
         * @access     Private
         * @return     Boolean
         * */
        private function isValidFilesize($filesize) {
            if($filesize > $this->maxSize) {
                return false;
            }
            return true;
        }
        /**
         * Get upload error info
         *
         * @param         Void
         * @access     Public
         * @return     Array upload error info
         */
        public function getErrorInfo() {
            return $this->errorInfo;
        }
    }
?>


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载