class Upload{
//错误信息
private $errorNo;
private $errorMsg;
//文件类型
private $ext;
//允许的文件类型
private $allowExt;
//文件的大小
private $size;
//允许的文件大小
private $allowSize;
//存放图片的主文件名称
private $dir;
//子文件夹名称
private $dirSec;
//临时文件名
private $tmpName;
//分隔符
const DS = DIRECTORY_SEPARATOR;
public function __construct($file,$dir='upload',$allowExt=['jpg','jpeg','gif','png'],$allowSize = 2097152){
$this->errorNo = $file['error'];
$this->ext = $file['name'];
$this->size = $file['size'];
$this->tmpName=$file['tmp_name'];
$this->dir = $dir;
$this->allowExt=$allowExt;
$this->allowSize=$allowSize;
}
public function UpLoad(){
if(!$this->checkFile()){
return $this->errorMsg;
}
if(!$this->createDir()){
return $this->errorMsg;
};
echo $this->moveFile();
}
private function checkFile(){
if(!$this->checkError()){
$this->errorMsg='文件错误,无法上传!';
return false;
}
if(!$this->checkExt()){
$this->errorMsg='不是图片,无法上传!';
return false;
}
if(!$this->checkSize()){
$this->errorMsg='文件超过指定大小,无法上传';
return false;
}
return true;
}
//检查文件错误
private function checkError(){
if($this->errorNo!=0){
return false;
}
return true;
}
//检查文件类型
private function checkExt(){
if(!in_array(pathinfo($this->ext)['extension'],$this->allowExt)){
return false;
}
return true;
}
//检查文件大小
private function checkSize(){
if($this->size > $this->allowSize){
return false;
}
return true;
}
//创建文件夹
private function createDir(){
$this->dirSec = $this->dir.self::DS.date('Y-m-d');
if(!file_exists($this->dir)){
if(!(mkdir($this->dir) && mkdir($this->dirSec))){
$this->errorMsg='主目录创建失败';
return false;
}
}elseif(!file_exists($this->dirSec)){
if(!mkdir($this->dirSec)){
$this->errorMsg='子目录创建失败';
return false;
}
}
return true;
}
//移动文件
private function moveFile(){
$imgName = date('YmdHis').'_'.mt_rand(10000,99999);
move_uploaded_file($this->tmpName,$this->dirSec.self::DS.$imgName.'.'.pathinfo($this->ext)['extension']);
return $this->dirSec.self::DS.$imgName.'.'.pathinfo($this->ext)['extension'];
}
}
自己写了一个,拿去直接用 $file = $_FILES['img'];
//new Upload(获取的文件信息,上传的文件夹,允许的文件类型,允许的文件大小); $upload = new Upload($file,'upload',['gif','png','jpg','jpeg'],444444444); $upload->UpLoad();