php上傳文件類
阿新 • • 發佈:2017-07-16
後綴 ret fin ado new 自己 public lower 文件上傳
<?php class 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上傳文件類