php面向对象之文件上传类

upfile=$_FILES[$name];
        $this->path=rtrim($path,"/")."/";
      
    }
      
    public function __set($param,$value){
        $this->$param=$value;
    }
      
    public function __get($param){
        return $this->$param;
    }
      
    //验证上传的错误号
    private function checkError(){
        if($this->upfile['error']>0){
            switch($this->upfile['error']){
                case 1: $info="上传文件大小超出PHP配置文件的设置"; break;
                case 2: $info="上传文件大小超过了表单中MAX_FILE_SIZE指定的值"; break;
                case 3: $info="文件只有部分被上传。"; break;
                case 4: $info="没有文件被上传。"; break;
                case 6: $info="找不到临时文件夹。"; break;
                case 7: $info="文件写入失败。"; break;
                default: $info="未知错误"; break;
            }
            $this->error=$info;
            return false;
        }
        return true;
    }
      
    //验证上传类型
    private function checkType(){
        if(count($this->typelist)>0){
            if(!in_array($this->upfile['type'],$this->typelist)){
                $this->error="上传文件类型错误:".$upfile['type'];
                return false;
            }
        }
        return true;
    }
      
    //验证大小
    private function checkSize(){
        if($this->maxsize>0 && $this->upfile['size']>$this->maxsize){
            $this->error="上传文件大小超出了允许范围!".$maxsize;
            return false;
        }
        return true;
    }
      
    //处理上传的文件名
    private function makeName(){
        do{
        //随机一个文件名,格式:时间戳+4位随机数+源后缀名
        $newname = time().rand(1000,9999).".".pathinfo($this->upfile['name'],PATHINFO_EXTENSION);
        }while(file_exists($this->path.$newname)); //判断随机的文件名是否存在。
        $this->fileinfo['savename']=$newname;
        return true;
    }
      
    //移动上传文件
    private function movefile(){
        if(is_uploaded_file($this->upfile['tmp_name'])){
            if(move_uploaded_file($this->upfile['tmp_name'],$this->path.$this->fileinfo['savename'])){
                return true;
            }else{
                $this->error='执行上传文件移动失败!';
            }
        }else{
            $this->error='不是一个有效的上传文件!';
        }
        return false;
    }
    //执行上传
    public function upload(){
        return ($this->checkError() && $this->checkType() && $this->checkSize() && $this->makeName() && $this->movefile());
    }
      
}
/*
//创建上传对象
$upfile = new FileUpload("pic","./public/uploads/");
//初始化属性
$upfile->filetype="";
$upfile->maxsize="";
//执行上传(成功返回true,失败返回false)
if($upfile->upload()){
    echo $upfile->fileinfo['savename']; //获取上后的文件名
}else{
    echo $upfile->error; //获取上传失败信息
}
*/

当前标题:php面向对象之文件上传类
分享URL:http://ybzwz.com/article/jdgpej.html