<?php/*** 檔案上傳類* @author lijiamin* @time 2017-02-17* @email 1195989301@qq.com*/class Upload{private $allowExt = array('gif','jpg','jpeg','bmp','png','swf');//限制檔案上傳的尾碼名private $maxSize = 1;//限制最大檔案上傳1M/*** 擷取檔案的資訊* @param str $flag 上傳檔案的標識* @return arr 上傳檔案的資訊數組*/public function getInfo($flag){return $_FILES[$flag];}/*** 擷取檔案的尾碼* @param str $filename 檔案名稱* @return str 副檔名*/public function getExt($filename){return pathinfo($filename,PATHINFO_EXTENSION);}/*** 檢測上傳檔案是否合法* @param str $filename 檔案名稱* @return bool 副檔名是否合法*/private function checkExt($filename){$ext = $this->getExt($filename);return in_array($ext,$this->allowExt);}/*** 檢測檔案大小是否超過限制* @param int size 檔案大小* @return bool 檔案大小是否超過限制*/public function checkSize($size){return $size < $this->maxSize * 1024 * 1024;}/*** 隨機的檔案名稱* @param int $len 隨機檔案名稱的長度* @return str 隨機字串*/public function randName($len=6){return substr(str_shuffle('abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ234565789'),0,$len);}/*** 建立檔案上傳到的路徑* @return str 檔案上傳的路徑*/ public function createDir(){//上傳檔案路徑$dir = './upload/'.date('Y/m/d',time());//判斷檔案夾是否存在,不存在則建立if(is_dir($dir) || mkdir($dir,0777,true)){return $dir;}}/*** 檔案上傳* @param str $flag 檔案上傳標識* @return array 返回上傳檔案名稱、儲存路徑*/public function uploadFile($flag){if($_FILES[$flag]['name'] === '' || $_FILES[$flag]['error'] !== 0){echo "沒有上傳檔案";return;}$info = $this->getInfo($flag);if(!$this->checkExt($info['name'])){echo "不支援的檔案類型";return;}if(!$this->checkSize($info['size'])){echo "檔案大小超過限制";return;}$filename = $this->randName().'.'.$this->getExt($info['name']);$dir = $this->createDir();if(!move_uploaded_file($info['tmp_name'], $dir.'/'.$filename)){echo "檔案上傳失敗";}else{return array('filename'=>$filename,'dir'=>$dir);}}}?>