<?php
/*
燕十八 公益PHP培训
课堂地址:YY频道88354001
学习社区:www.zixue.it
思路:多文件上传或的数据格式是$_FILES['name'].$_FIELS['error']..都是数组的格式,只要把单文件上传的格式也转变成多文件上传的格式就可以实现多文件上传了
文件上传类
1:处理文件上传的大小
2:处理文件上传的后缀
3:处理文件上传的错误报告
4:处理文件上传的目录
5:处理文件上传的随机名称
其值为 0,没有错误发生,文件上传成功。
*/
defined('ACC')||exit('NO PERMISSION');
class Upload{
//allow文件的后缀
protected $filesExt = "jpg,png,gif,bmp,jpeg,rar,exe";
//放回错误信息
public $upErr = '图片上传成功!';
//返回的文件路径
public $filesPath = array();
//默认大小为1M;
protected $maxSize = 1;
//上传的文件$_FILES的temp量
protected $files = null;
//上传文件的错误信息
protected $error = array(
0=>"文件上传成功",
1=>'文件上传过大',
2=>'上传文件超过了HTML表单的POST的数据量',
3=>'文件只有部分被上传',
4=>'请上传完整文件',
6=>'找不到临时文件夹',
7=>'文件写入失败',
8=>'上传不支持此格式文件',
9=>'上传文件过大',
10=>'创建文件夹失败',
11=>'移动文件出错',
12=>'文件重命名失败'
);
//文件上传方法
public function Up($files){
$rs = array_values($files);
$files = $rs[0];
if(is_array($files['name'])){
$this->files = $files;
}else{
foreach($files as $key => $value){
$res[$key][0] = $value;
}
$this->files = $res;
}
for($i=0;$i<count($this->files['name']);$i++){
if($this->files['error'][$i]!=0){
$this->upErr = $this->error[$this->files['error'][$i]];
return false;
}
if(!$this->IsExt($i)){
$this->upErr = $this->error[8];
return false;
}
if(!$this->Mk_dir()){
$this->upErr = $this->error[10];
return false;
}
if(!$this->IsMax($i)){
$this->upErr = $this->error[9];
return false;
}
if(!$this->FileRename()){
$this->upErr = $this->error[12];
return false;
}
if(!$this->MoveFiles($i)){
$this->upErr = $this->error[11];
return false;
}
}
if(count($this->filesPath)==1){
return $this->filesPath[0];
}else{
return $this->filesPath;
}
}
//获取文件后缀方法
protected function GetExt($i=0){
return end(explode('.',$this->files['name'][$i]));;
}
//判断后缀是否合法
protected function IsExt(){
if(in_array($this->GetExt(),explode(',',$this->filesExt))){
return true;
}else{
return false;
}
}
//获取文件大小的方法
protected function IsMax($i){
if($this->files['size'][$i] < $this->maxSize*(1024*1024)){
return true;
}else{
return false;
}
}
//生成目录方法
protected function Mk_dir(){
$dir = ROOT.'data/images/'.date('ym/d');
if(is_dir($dir)||mkdir($dir,0777,true)){
return true;
}else{
return false;
}
}
//生成随机文件名方法
protected function FileRename(){
$str = "abcdefghijklmnopqrstuvwxyz1234567890";
return date('ymd').substr(str_shuffle($str),0,6).'.'.$this->GetExt();
}
//将文件移动到指定目录
protected function MoveFiles($i){
$filesPath = ROOT."data/images/".date('ym/d').'/'.$this->FileRename();
if(move_uploaded_file($this->files['tmp_name'][$i],$filesPath)){
$filesPath = str_replace(ROOT,'',$filesPath);
$this->filesPath[] = $filesPath;
return true;
}else{
return false;
}
}
}