[php] /* 單個檔案上傳 功能 上傳檔案 配置允許的尾碼 配置允許的大小 擷取檔案尾碼 判斷檔案的尾碼 報錯 */ class UpTool{ protected $allowExt = 'jpg,jpeg,gif,bmp,png'; protected $maxSize = 1; //1M ,以M為單位 protected $file = null; //準備儲存上傳檔案資訊 protected $errno = 0; //錯誤碼 protected $error = array( 0=>'無錯', 1=>'上傳檔案大小超出系統限制', 2=>'上傳檔案的大小超出網頁表單限制', 3=>'檔案只有部分被上傳', 4=>'沒有檔案被上傳', 6=>'找不到臨時檔案夾', 7=>'檔案寫入失敗', 8=>'不允許的檔案尾碼', 9=>'檔案大小超出類的允許範圍', 10=>'建立目錄失敗', 11=>'檔案移動失敗' ); /* 上傳 */ public function up($key) { if (!isset($_FILES[$key])) { return false; } $f = $_FILES[$key]; //檢驗上傳是否成功 if ($f['error']) { $this->errno = $f['error']; return false; } //擷取尾碼 $ext = $this->getExt($f['name']); //檢查尾碼 if (!$this->isAllowExt($ext)) { $this->errno = 8; return false; } //檢查大小 if (!$this->isAllowSize($f['size'])) { $this->errno = 9; return false; } //建立目錄 $dir = $this->mk_dir(); if ($dir == false) { $this->errno = 10; return fasle; } //產生隨機檔案名稱 $newname = $this->randName() . '.' .$ext; //$dir = $dir . '/' .$newname; //移動 if(!move_uploaded_file($f['tmp_name'], $dir . '/' .$newname)) { $this->errno = 11; return false; } return true;//str_replace(ROOT, '', $dir); } public function getErr(){ return $this->error[$this->errno]; } /* parm string $exts 允許的尾碼 自動添加 允許的尾碼,和檔案的大小 */ public function setExt($exts) { $this->allowExt = $exts; } public function setSize($num) { $this->maxSize = $num; } /* string $file return string $ext 尾碼 */ protected function getExt($file) { $tmp = explode('.', $file); return end($tmp); } /* string $ext 檔案尾碼 return bool 防止大小寫問題 */ protected function isAllowExt($ext) { return in_array(strtolower($ext), explode(',', strtolower($this->allowExt))) ; } /* 檢查檔案的大小 */ protected function isAllowSize($size) { return $size <= $this->maxSize *1024*1024; } //按日期建立目錄的方法 protected function mk_dir() { $dir = 'images/' . date('Ym/d'); if(is_dir($dir) || mkdir($dir,0777,true)) { return $dir; } else { return false; } } /* 產生隨機檔案名稱 */ protected function randName($length = 6) { $str = 'abcdefghijkmnpqrstuvwxyz23456789'; return substr(str_shuffle($str),0,$length); } } form 表單[html] 另起頁面調用 [php] require('./UpTool.class.php'); $uptool = new UpTool(); $uptool->setExt('rar,doc'); $uptool->setSize(1); if ($uptool->up('pic')) { echo '上傳成功'; } else { echo '失敗'; echo $uptool->getErr(); }
http://www.bkjia.com/PHPjc/477843.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/477843.htmlTechArticle[php] /* 單個檔案上傳 功能 上傳檔案 配置允許的尾碼 配置允許的大小 擷取檔案尾碼 判斷檔案的尾碼 報錯 */ class UpTool{ protected $allowExt = jp...