/**
燕十八 公益PHP培訓
課堂地址:YY頻道88354001
學習社區:www.zixue.it
**/
html上傳表單:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<form method="post" action="up.php" enctype='multipart/form-data'>
<span>文件:</span><input type='file' name='file' ><br>
<input type='submit' value='上傳' ><br>
</form>
</body>
</html>
處理上傳後的php文件
<?php
if(isset($_FILES['file'])){
include 'uploadFile.class.php';
$up=new uploadFile('file');//file爲input的name值
$up->setAllowTypes('jpg,jpeg');//手動設置允許上傳的類型爲jpg,jpeg
$up->setAllowMaxSize(4);//手動設置上傳的最大容量爲4mb
if(!!$res=$up->upload()){
echo $res;
echo '上傳文件成功';
}else{
echo $up->getError();
echo '上傳失敗';
}
}
?>
文件上傳類:
<?php
//水平有限,目前只有單文件上傳
class uploadFile{
private $allowTypes='jpg,jpeg,gif,bmp';//允許上傳的文件類型
private $allowMaxSize=1;//允許文件的最大容量,1爲1mb的意思
private $_file;//存在上傳後的數組信息
private $error_num;//錯誤代碼
private $error_info=array(
0=>'成功',
1=>'大小超過upload_max_filesize',
2=>'大小超過MAX_FILE_SIZE',
3=>'文件只被部分上傳',
4=>'沒有上傳任何文件',
6=>'沒有指定upload_tmp_dir目錄',
7=>'文件寫入磁盤錯誤',
// 8=>'該類型文件不允許上傳',
// 9=>'文件太大',
10=>'文件不是通過http post上傳的',
11=>'文件移動失敗',
);//錯誤信息
public function __construct($name){//傳入文件input中的name值
$this->_file=$_FILES[$name];
}
//上傳操作
public function upload(){
//上傳失敗
if($this->_file['error']>0){
$this->error_num=$this->_file['error'];
return false;
}
//類型不通過
if(!$this->checkType()){
$this->error_num=8;
$this->error_info[8]='只能是以下類型文件:'.$this->allowTypes;
return false;
}
//大小超過最大值
if(!$this->checkSize()){
$this->error_num=9;
$this->error_info[9]='文件最大不能超過:'.$this->allowMaxSize.'mb';
return false;
}
//文件不是通過http post上傳的
if(!is_uploaded_file($this->_file['tmp_name'])){
$this->error_num=10;
return false;
}
$newdir='./images'.date('/Ym/d').'/';
if(!is_dir($newdir)){
mkdir($newdir,0777,true);//創建存放圖片的目錄
}
$newpath=$newdir.$this->getRandName().'.'.$this->getFileType();
if(!move_uploaded_file($this->_file['tmp_name'],$newpath)){
$this->error_num=11;
return false;
}else{
return $newpath;
}
}
//檢查文件類型是否符合
private function checkType(){
$type=explode(',',$this->allowTypes);
$filetype=$this->getFileType();
if(!in_array($filetype,$type)){
return false;
}else{
return true;
}
}
//獲取文件類型
private function getFileType(){
$arr=pathinfo($this->_file['name']);
return strtolower($arr['extension']);
}
//檢查文件大小
private function checkSize(){
$filesize=$this->_file['size'];
if($filesize>$this->allowMaxSize*1024*1024){
return false;
}else{
return true;
}
}
//隨機文件名
private function getRandName(){
$str='abcdefghijklmnopqrstuvwxyz';
return substr(str_shuffle($str),0,8).time();
}
//獲取錯誤信息
public function getError(){
return $this->error_info[$this->error_num];
}
//手動設置允許的文件上傳類型
public function setAllowTypes($str){
$this->allowTypes=$str;
}
//手動設置最大上傳大小
public function setAllowMaxSize($size){
$this->allowMaxSize=$size;
}
}