Home >Backend Development >PHP Tutorial >PHP file upload classification

PHP file upload classification

高洛峰
高洛峰Original
2017-02-18 16:13:571438browse

<?php
/**
* 文件上传类
* @author lijiamin
* @time 2017-02-17
* @email 1195989301@qq.com
*/
class Upload{

private $allowExt = array(&#39;gif&#39;,&#39;jpg&#39;,&#39;jpeg&#39;,&#39;bmp&#39;,&#39;png&#39;,&#39;swf&#39;);//限制文件上传的后缀名
private $maxSize = 1;//限制最大文件上传1M

/**
* 获取文件的信息
* @param str $flag 上传文件的标识
* @return arr 上传文件的信息数组
*/
public function getInfo($flag){
return $_FILES[$flag];
}

/**
* 获取文件的后缀
* @param str $filename 文件名
* @return str 文件扩展名
*/
public function getExt($filename){
return pathinfo($filename,PATHINFO_EXTENSION);
}

/**
* 检测上传文件是否合法
* @param str $filename 文件名
* @return bool 文件扩展名是否合法
*/
private function checkExt($filename){
$ext = $this->getExt($filename);
return in_array($ext,$this->allowExt);
}

/**
* 检测文件大小是否超过限制
* @param int size 文件大小
* @return bool 文件大小是否超过限制
*/
public function checkSize($size){
return $size < $this->maxSize * 1024 * 1024;
}

/**
* 随机的文件名
* @param int $len 随机文件名的长度
* @return str 随机字符串
*/
public function randName($len=6){
return substr(str_shuffle(&#39;abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ234565789&#39;),0,$len);
}

/**
* 创建文件上传到的路径
* @return str 文件上传的路径
*/ 
public function createDir(){
//上传文件路径
$dir = &#39;./upload/&#39;.date(&#39;Y/m/d&#39;,time());

//判断文件夹是否存在,不存在则新建
if(is_dir($dir) || mkdir($dir,0777,true)){
return $dir;
}
}

/**
* 文件上传
* @param str $flag 文件上传标识
* @return array 返回上传文件名、保存路径
*/
public function uploadFile($flag){
if($_FILES[$flag][&#39;name&#39;] === &#39;&#39; || $_FILES[$flag][&#39;error&#39;] !== 0){
echo "没有上传文件";
return;
}

$info = $this->getInfo($flag);

if(!$this->checkExt($info[&#39;name&#39;])){
echo "不支持的文件类型";
return;
}
if(!$this->checkSize($info[&#39;size&#39;])){
echo "文件大小超过限制";
return;
}
$filename = $this->randName().&#39;.&#39;.$this->getExt($info[&#39;name&#39;]);

$dir = $this->createDir();

if(!move_uploaded_file($info[&#39;tmp_name&#39;], $dir.&#39;/&#39;.$filename)){
echo "文件上传失败";
}else{
return array(&#39;filename&#39;=>$filename,&#39;dir&#39;=>$dir);
}
}

}
?>


For more PHP file upload categories, please pay attention to the PHP Chinese website for related articles!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php in_array syntaxNext article:php in_array syntax