文件上传类 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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值