<?php
/**
* 文件名称:文件上传类
* 文件作者:张真贵
* 创建时间:2015-10-09
* 实例化 upFile 调用 upload($key) 方法 $key为上传是input框里面的name值 注意 用$_POST是接受不到的
* return 文件的路径和名称
*/
/**
* 步骤
* 1、检测文件是否上传
* 2、检测文件后缀是否合法
* 3、检测文件大小
* 4、创建日期目录
* 5、生成随机文件
* 6、保存上传文件
*/
/**
* 使用方法
* 实例化upFile
* 调用up方法
* 成功则显示结果
* 否则调用getError()方法显示错误类型
*/
class upFile{
protected $allovExt = array('.jpg','.jpeg','.gif','.bmp','.png'); //允许的后缀
protected $maxSize = 1; //文件的大小限制 M为单位
protected $errorNum = 0; //错误信息
protected $upArr = null; //接收的文件数组
protected $ext = ''; //后缀名
protected $dir = ''; //生成的目录
protected $fileName = ''; //生成的随机文件名
protected $path = ''; //上传文件保存的路径
protected $errorArr = array( //错误信息数组
0=>'无错',
1=>'文件大小超出系统限制',
2=>'文件大小超出网页限制',
3=>'文件只有部分被上传',
4=>'没有选择上传图片',
6=>'找不到临时文件',
7=>'文件写入失败',
8=>'不允许的文件后缀',
9=>'文件大小超出类的范围',
10=>'创建目录失败',
11=>'移动失败',
12=>'文件名错误'
);
public function __construct(){
if (!count($_FILES)) exit('非法访问');
}
/**
* 获取后缀名
* arg: $file
* return: string
*/
protected function getExt($file){
if (!is_string($file)) { //如果不是字符串
# code...
$this->errorNum = 12;
return false;
}
return strrchr($file,'.');
}
/**
* 判断后缀名
*/
protected function allowExt($ext){
return in_array( strtolower($ext) , $this->allovExt ); //如果为true则允许,false则不允许
}
/**
* 判断文件是否在允许大小范围
*/
protected function allowSize($size){
return $size < $this->maxSize*1024*1024;
}
/**
* 创建目录
* arg
* return $path or false
*/
protected function mk_dir(){
$dir = ROOT.'data/upload/'.date('Ymd');
if (is_dir($dir) || mkdir($dir,0777,true)) {
# code...
return $dir;
}else{
return false;
}
}
/**
* 生成随机文件
* arg $n
* return string
*/
protected function randName($n=6){ //$n 代表截取长度
$str = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ0123456789';
$str = str_shuffle($str); //随机打乱一个字符串
$str = substr($str,0,$n); //截取子字符串
return $str;
}
/**
* 文件上传
* arg
* return
*/
public function upload($key){
if (!isset($_FILES[$key])) {
# code...
return '参数错误';
}
$this->upArr = $_FILES[$key]; //上传的数组
//如果上传没成功 即 $_FILES[$key]['error'] 错误信息不为 0
if ($this->upArr['error']) {
# code...
$this->errorNum = $this->upArr['error'];
return false;
}
//获取后缀名
$file = $this->upArr['name']; //上传前的文件名
$this->ext = $this->getExt($file); //得到的后缀名
// exit($ext);
//检测后缀名
if( !$this->allowExt($this->ext) ){
$this->errorNum = 8;
return false;
}
//检测文件大小
$fileSize = $this->upArr['size'];
if( !$this-> allowSize($fileSize) ){
$this->errorNum = 9;
return false;
}
//安全检验都通过
//开始创建目录
$this->dir = $this->mk_dir();
if(!$this->dir){
$this->errorNum = 10;
return false;
}
//生产随机文件
$this->fileName = $this->randName();
//拼接形成最后文件路径和名字
$this->path = $this->dir.'/'.$this->fileName.$this->ext;
//移动保存文件
if( !move_uploaded_file($this->upArr['tmp_name'], $this->path) ){
$this->errorNum = 11;
return false;
}
return str_replace('D:/WWW/study/food', '..', $this->path);
}
/**
* 错误处理
* arg : $n错误码
* return string
*/
public function getError(){
return $this->errorArr[$this->errorNum];
}
}
?>