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 表單<form action="up.php" method="post" enctype="multipart/form-data">
用戶名:<input type="text" name="username" /> <br/>
頭像: <input type="file" name="pic" />
<input type="submit" value="提交" />
</form>
另起頁麵調用
require('./UpTool.class.php');
$uptool = new UpTool();
$uptool->setExt('rar,doc');
$uptool->setSize(1);
if ($uptool->up('pic')) {
echo '上傳成功';
} else {
echo '失敗';
echo $uptool->getErr();
}
最後更新:2017-04-04 07:03:12