單文件上傳類---圖片上傳

<?php 
class upload
{
    private $allow = ['image'];

    // 單文件上傳
    public function single(  )
    {
        // error
        $key = key($_FILES);
        if(empty($key)){
            return '您的文件過大, 請從新上傳';
        }

        $error = $_FILES[$key]['error'];
        if($error > 0){
            switch($error){
                case '1': return '您的文件過大, 請從新上傳'; 
                case '2': return '您的文件過大, 請從新上傳';
                case '3': return '請檢查您的網絡';
                case '4': return '請上傳您的文件';
                case '6': return '服務器繁忙';
                case '7': return '服務器繁忙';
            }
        }

        // post
        if(!is_uploaded_file( $_FILES[$key]['tmp_name'])){
            return '非法上傳';
        }

        // 文件類型
        $type = strtok($_FILES[$key]['type'], '/');
        if( !in_array($type, $this->allow) ){
            return '文件類型不符';
        }

        // 新的文件名
        // 20180208xxxxxx.jpg
        $suffix = strrchr($_FILES[$key]['name'], '.');
        $fileName = date('Ymd').uniqid().$suffix;

        // 新的目錄
        // upload/2018/02/08/
        $dir = UPLOAD.date('/Y/m/d/');
        if( !file_exists($dir) ){
            mkdir($dir, 0777, true);
        }

        // 移動臨時文件
        if( move_uploaded_file($_FILES[$key]['tmp_name'], $dir.$fileName)){
            $file[] = $fileName;
            return $file;
        }
        return '上傳失敗';
    }

    public function fileType($condition = '')
    {
        if(!is_array($condition)){
            return false;
        }else{
            $this->allow = $condition;
        }
        return $this;
    }
}
相關文章
相關標籤/搜索