PHP文件上傳類

class Upload{

    //錯誤信息
    private $errorNo;
    private $errorMsg;
    //文件類型
    private $ext;
    //允許的文件類型
    private $allowExt;
    //文件的大小
    private $size;
    //允許的文件大小
    private $allowSize;
    //存放圖片的主文件名稱
    private $dir;
    //子文件夾名稱
    private $dirSec;
    //臨時文件名
    private $tmpName;
    //分隔符
    const DS = DIRECTORY_SEPARATOR;

    public function __construct($file,$dir='upload',$allowExt=['jpg','jpeg','gif','png'],$allowSize = 2097152){
        $this->errorNo = $file['error'];
        $this->ext = $file['name'];
        $this->size = $file['size'];
        $this->tmpName=$file['tmp_name'];
        $this->dir = $dir;
        $this->allowExt=$allowExt;
        $this->allowSize=$allowSize;
    }

    public function UpLoad(){
        if(!$this->checkFile()){
            return $this->errorMsg;
        }

        if(!$this->createDir()){
            return $this->errorMsg;
        };
        echo $this->moveFile();
    }

    private function checkFile(){
        if(!$this->checkError()){
            $this->errorMsg='文件錯誤,無法上傳!';
            return false;
        }
        if(!$this->checkExt()){
            $this->errorMsg='不是圖片,無法上傳!';
            return false;
        }
        if(!$this->checkSize()){
            $this->errorMsg='文件超過指定大小,無法上傳';
            return false;
        }

        return true;
    }

    //檢查文件錯誤
    private function checkError(){
        if($this->errorNo!=0){
            return false;
        }
        return true;
    }

    //檢查文件類型
    private function checkExt(){
        if(!in_array(pathinfo($this->ext)['extension'],$this->allowExt)){
            return false;
        }
        return true;
    }

    //檢查文件大小
    private function checkSize(){
        if($this->size > $this->allowSize){
            return false;
        }
        return true;
    }

    //創建文件夾
    private function createDir(){
        $this->dirSec = $this->dir.self::DS.date('Y-m-d');
        if(!file_exists($this->dir)){
            if(!(mkdir($this->dir) && mkdir($this->dirSec))){
                $this->errorMsg='主目錄創建失敗';
                return false;
            }
        }elseif(!file_exists($this->dirSec)){
            if(!mkdir($this->dirSec)){
                $this->errorMsg='子目錄創建失敗';
                return false;
            }
        }
        return true;
    }

    //移動文件
    private function moveFile(){
        $imgName = date('YmdHis').'_'.mt_rand(10000,99999);
        move_uploaded_file($this->tmpName,$this->dirSec.self::DS.$imgName.'.'.pathinfo($this->ext)['extension']);
        return $this->dirSec.self::DS.$imgName.'.'.pathinfo($this->ext)['extension'];
    }
}

自己寫了一個,拿去直接用
$file = $_FILES['img'];

//new Upload(獲取的文件信息,上傳的文件夾,允許的文件類型,允許的文件大小);
$upload = new Upload($file,'upload',['gif','png','jpg','jpeg'],444444444);
$upload->UpLoad();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章