標籤:get return his one class load move 類型資訊 const
<?phpclass Upload { private $_max_size; private $_type_map; private $_allow_ext_list; private $_allow_mime_list; private $_upload_path; private $_prefix; private $_error;//當前的錯誤資訊 public function getError() { return $this->_error; } public function __construct() { $this->_max_size = 1024*1024; $this->_type_map = array( ‘.png‘ => array(‘image/png‘, ‘image/x-png‘), ‘.jpg‘ => array(‘image/jpeg‘, ‘image/pjpeg‘), ‘.jpeg‘ => array(‘image/jpeg‘, ‘image/pjpeg‘), ‘.gif‘ => array(‘image/gif‘), ); $this->_allow_ext_list = array(‘.png‘, ‘.jpg‘); $allow_mime_list = array(); foreach($this->_allow_ext_list as $value) { //得到每個尾碼名 $allow_mime_list = array_merge($allow_mime_list, $this->_type_map[$value]); } // 去重 $this->_allow_mime_list = array_unique($allow_mime_list); $this->_upload_path = ‘./‘; $this->_prefix = ‘‘; } public function __set($p, $v) {//屬性重載 $allow_set_list = array(‘_upload_path‘, ‘_prefix‘, ‘_allow_ext_list‘, ‘_max_size‘); //可以不加:_ 進行設定 if(substr($p, 0, 1) !== ‘_‘) { $p = ‘_‘ . $p; } $this->$p = $v; } /** * 上傳單個檔案 */ public function uploadOne($tmp_file) { # 是否存在錯誤 if($tmp_file[‘error‘] != 0) { $this->_error = ‘檔案上傳錯誤‘; return false; } # 尺寸 if ($tmp_file[‘size‘] > $this->_max_size) { $this->_error = ‘檔案過大‘; return false; } # 類型 # 保證修改允許的尾碼名,就可以影響到$allow_ext_list和$allow_mime_list # 設定一個尾碼名與mime的映射關係 # 尾碼,從原始檔案名中提取 $ext = strtolower(strrchr($tmp_file[‘name‘], ‘.‘)); if (!in_array($ext, $this->_allow_ext_list)) { $this->_error = ‘類型不合法‘; return false; } # MIME, type元素。 // $allow_mime_list = array(‘image/png‘, ‘image/gif‘, ‘image/jpeg‘, ‘image/pjpeg‘, ‘image/x-png‘); if (!in_array($tmp_file[‘type‘], $this->_allow_mime_list)) { $this->_error = ‘類型不合法‘; return false; } //PHP自己擷取檔案的mime,進行檢測 $finfo = new Finfo(FILEINFO_MIME_TYPE);//獲得一個可以檢測檔案MIME類型資訊的對象 $mime_type = $finfo->file($tmp_file[‘tmp_name‘]);//檢測 if (!in_array($mime_type, $this->_allow_mime_list)) { $this->_error = ‘類型不合法‘; return false; } # 移動 # 上傳檔案儲存體地址 //建立子目錄 $subdir = date(‘YmdH‘) . ‘/‘; if(!is_dir($this->_upload_path . $subdir)) {//檢測是否存在 //不存在 mkdir($this->_upload_path . $subdir); } # 科學起名 $upload_filename = uniqID($this->_prefix, true) . $ext; if (move_uploaded_file($tmp_file[‘tmp_name‘], $this->_upload_path . $subdir . $upload_filename)) { // 移動成功,返迴文件名 return $subdir . $upload_filename; } else { // 移動失敗 $this->_error = ‘移動失敗‘; return false; } }}
php上傳檔案類