php工具类之【文件上传类】

class Upload{	
    // 上传文件的最大值
    public $maxSize = -1;
    // 允许上传的文件后缀
    //  留空不作后缀检查
    public $allowExts = array();
    // 使用对上传图片进行缩略图处理
    public $thumb   =  false;
    // 缩略图最大宽度
    public $thumbMaxWidth=20;
    // 缩略图最大高度
    public $thumbMaxHeight=20;
    // 错误信息
    public $error = '';
    // 上传成功的文件信息
    public $success =array('file'=>'', 'thumb'=>'', 'name'=>'', 'type'=>'', 'size'=>0);

    public function __construct($maxSize='',$allowExts='',$thumb=false,$thumbMaxWidth=100,$thumbMaxHeight=100) {
        if(!empty($maxSize) && is_numeric($maxSize)) {
            $this->maxSize = $maxSize;
        }
        if(!empty($allowExts)) {
            if(is_array($allowExts)) {
                $this->allowExts = array_map('strtolower',$allowExts);
            }else {
                $this->allowExts = explode(',',strtolower($allowExts));
            }
        }
        $this->thumb = $thumb;
        $this->thumbMaxWidth = $thumbMaxWidth;
        $this->thumbMaxHeight = $thumbMaxHeight;
    }
	
	/**
	 * 保存文件,并根据设置决定是否生成缩略图
	 * @param $_FILES $file--要保存的附件
	 * @param String $path--要保存附件的地址
	 * @return boolean
	 */
	public function saveFile($file,$path){
		//判断文件是否存在
		if(empty($file['size'])||empty($file['tmp_name']))
		{
			$this->error = "1-传入的附件不存在";
			return false;	
		}
        //检查文件大小
        if(!$this->_checkSize($file['size'])) {
            $this->error = '2-上传文件大小不符!';
            return false;
        }
		//获取文件的后缀名
		$fileExt = $this->_fileExt($file['name']);
	 	//检查文件类型
        if(!$this->_checkExt($fileExt)) {
            $this->error ='3-上传文件类型不允许';
            return false;
        }
        // 如果是图像文件 检测文件格式
        if(in_array($fileExt,array('gif','jpg','jpeg','bmp','png','swf')) && false === getimagesize($file['tmp_name'])) {
            $this->error = '4-非法图像文件';
            return false;
        }
        //生成文件的完整存储路径
        $childPath = $this->_getFilePath($path);
        if(empty($childPath)){
        	$this->error = "5-出入的文件夹路径不具有写权限";
        	return false;
        }
        //生成文件最终存储路径
        $absolutePath = $path.'/'.$childPath;
        $newFileName = date('YmdHis').$this->_random(4);
        $storePath = $absolutePath.'/'.$newFileName.'.'.$fileExt;
        //保存上传的文件
        if(@copy($file['tmp_name'],$storePath) || (function_exists("move_uploaded_file")&&@move_uploaded_file($file['tmp_name'],$storePath)))
        {
        	@unlink($file['tmp_name']);
        	$this->success['file'] = $childPath.'/'.$newFileName.'.'.$fileExt;
        	$this->success['name'] = $newFileName.'.'.$fileExt;
        	$this->success['type'] = $fileExt;
        	$this->success['size'] = $file['size'];
        }else if(is_readable($file['tmp_name'])){
        	$fp = @fopen($file['tmp_name'], 'rb');
			@flock($fp, 2);
			$attachedContent = @fread($fp, $file['size']);
			@fclose($fp);

			$fp = @fopen($storePath, 'wb');
			@flock($fp, 2);
			if(@fwrite($fp, $attachedContent)){
				@unlink($file['tmp_name']);
				$this->success['file'] = $childPath.'/'.$newFileName.'.'.$fileExt;
        		$this->success['name'] = $newFileName.'.'.$fileExt;
        		$this->success['type'] = $fileExt;
        		$this->success['size'] = $file['size'];
			}
			@fclose($fp);
        }else{
        	$this->error = "6-文件上传保存错误!";
        	return false;
        }

        if($this->thumb && in_array($fileExt,array('gif','jpg','jpeg','bmp','png'))) {
            $image =  getimagesize($storePath);
            if(false !== $image) {
                //是图像文件生成缩略图
                $thumbWidth	 =	$this->thumbMaxWidth;
                $thumbHeight =	$this->thumbMaxHeight;
                $thumbname   = $absolutePath.'/'.$newFileName.'.thumb.jpg';
                $this->success['thumb'] = $childPath.'/'.$newFileName.'.thumb.jpg';
                // 生成图像缩略图
                require_once dirname(__FILE__).'/Image.class.php';
				Image::thumb($storePath,$thumbname,'',$thumbWidth,$thumbHeight,true);
            }
        }
        return true;
    }
	/***
	 * 替换已经存在的文件。
	 * @param:$file-上传的文件。
	 * @param:$absolutePath-源文件的绝对路径。
	 * @return:0-成功;其他-不成功。
	 * */
	public function replaceFile($file,$absolutePath)
	{
		//判断文件是否存在
		if(empty($file['size'])||empty($file['tmp_name']))
		{
			$this->error = "1-传入的附件不存在";
			return false;	
		}
        //检查文件大小
        if(!$this->_checkSize($file['size'])) {
            $this->error = '2-上传文件大小不符!';
            return false;
        }
		//获取文件的后缀名
		$fileExt = $this->_fileExt($file['name']);
	 	//检查文件类型
        if(!$this->_checkExt($fileExt)) {
            $this->error ='3-上传文件类型不允许';
            return false;
        }
		$new_name = $absolutePath;
		$tmp_name = $file['tmp_name'];

		if(@copy($tmp_name, $new_name) || (function_exists('move_uploaded_file') && @move_uploaded_file($tmp_name, $new_name)) || @rename($tmp_name, $new_name)) {
			@unlink($tmp_name);
			return true;
		}elseif(is_readable($tmp_name)) {
			$fp = @fopen($tmp_name, 'rb');
			@flock($fp, 2);
			$attachedfile = @fread($fp, $file['size']);
			@fclose($fp);

			$fp = @fopen($new_name, 'wb');
			@flock($fp, 2);
			if(@fwrite($fp, $attachedfile)) {
				@fclose($fp);
				@unlink($tmp_name);
				return true;
			}
			@fclose($fp);
		}else{
			$this->error = "4-文件上传保存错误!";
			return false;
		}
	}
    
	/**
	 * 获取文件名后缀
	 * @param string $filename--文件名称
	 * @return string--文件后缀
	 **/
	private function _fileExt($filename) {
		return strtolower(trim(substr(strrchr($filename, '.'), 1)));
	}
 	/**
 	 * 检查文件是否允许上传
 	 * @param String $ext--文件的后缀名
 	 * @return boolean--true-允许;false-不允许
 	 */
 	private function _checkExt($ext) {
        if(!empty($this->allowExts))
            return in_array($ext,$this->allowExts,true);
        return true;
    }
    /**
     * 检查文件大小是否超出限制
     * @param int $size--文件实际大小
     * @return boolean
     */
    private function _checkSize($size) {
        return !($size > $this->maxSize) || (-1 == $this->maxSize);
    }
	/**
	 * 生成文件的上传路径
	 * @param String $relativePath--用户传入的相对路径
	 * @return string--为创建出目录返回‘’;创建成功返回用户传入相对路径下生成出存储路径
	 */
	private function _getFilePath($relativePath) {
		$name1 = gmdate('Ym');
		$name2 = gmdate('j');

		$newfilename = $relativePath.'/'.$name1;
		if(!is_dir($newfilename)) {
			if(!@mkdir($newfilename)) {
				return '';
			}
		}
		$newfilename .= '/'.$name2;
		if(!is_dir($newfilename)) {
			if(!@mkdir($newfilename)) {
				return '';
			}
		}
		return $name1.'/'.$name2;
	}
	/**
	 * 生成随机数
	 * @param int $length--生成的随机数长度
	 * @param int $numeric
	 * @return string--随机数
	 */
	private function _random($length, $numeric = 0) {
		PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
		$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
		$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
		$hash = '';
		$max = strlen($seed) - 1;
		for($i = 0; $i < $length; $i++) {
			$hash .= $seed[mt_rand(0, $max)];
		}
		return $hash;
	}
}

猜你喜欢

转载自student-lp.iteye.com/blog/2104016