小标
2019-02-22
来源 :
阅读 1073
评论 0
摘要:本文主要向大家介绍了PHP语言学习之PHP文件上传类,通过具体的内容向大家展示,希望对大家学习php语言有所帮助。
本文主要向大家介绍了PHP语言学习之PHP文件上传类,通过具体的内容向大家展示,希望对大家学习php语言有所帮助。

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();
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言PHP频道!
喜欢 | 1
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号