<?php
class upload
{protected $maxSize=2097152;//允许上传的最大值
protected $allowExt;//上传文件扩展名
protected $allowMime;//允许的mime类型
protected $uploadPath;//上传路径
protected $imgFlag;//检测上传文件是否为真正的图片
protected $file;//通过post获得$_FILES
protected $error;//获得错号
protected $ext;//文件扩展名
protected $destination;//上传路径
protected $uniName;//文件名
public function __construct($fileName='myFile',$uploadPath='./uploads',$imgFlag=true,$maxSize=5242880,$allowExt=array('jpeg','jpg','png','gif'),$allowMime=array('image/jpeg','image/png','image/gif')){//构造函数
$this->fileName=$fileName;
$this->maxSize=$maxSize;
$this->allowMime=$allowMime;
$this->allowExt=$allowExt;
$this->uploadPath=$uploadPath;
$this->imgFlag=$imgFlag;
$this->file=$_FILES[$this->fileName];
}
protected function checkError(){
if(!is_null($this->file)){
if($this->file['error']>0){
switch($this->file['error']){
case 1:
$this->error='超过了PHP配置文件中upload_max_filesize选项的值';
break;
case 2:
$this->error='超过了表单中MAX_FILE_SIZE设置的值';
break;
case 3:
$this->error='文件部分被上传';
break;
case 4:
$this->error='没有选择上传文件';
break;
case 6:
$this->error='没有找到临时目录';
break;
case 7:
$this->error='文件不可写';
break;
case 8:
$this->error='由于PHP的扩展程序中断文件上传';
break;
}
return false;
}else{
return true;
}
}else{
$this->error='文件上传出错';
return false;
}
}
protected function checkSize(){ //验证上传文件大小
if($this->file['size']>$this->maxSize)
{$this->error="上传文件过大";
return false;}
else
return true;
}
protected function checkExt(){//验证文件扩展名
$this->ext=strtolower(pathinfo($this->file['name'],PATHINFO_EXTENSION));
if(!in_array($this->ext,$this->allowExt)){
$this->error='不允许的扩展名';
return false;
}
return true;
}
protected function checkMime(){//验证文件mime
if(!in_array($this->file['type'],$this->allowMime)){
$this->error="类型不允许".$this->file['type'];
return false;
}else
return true;
}
protected function checkTrueImg()//验证图片是否为真正的图片还是文本文件修改扩张名后的文件
{if($this->imgFlag){
if(!@getimagesize($this->file['tmp_name'])){
$this->error="这不是真正的图片";
return false;
}else
return true;
}
}
protected function checkHttpPost(){//验证是否是通过http post方式上传的
if(!is_uploaded_file($this->file['tmp_name'])){
$this->error="文件不是通过http post方式传上来的";
return false;
}else
return true;
}
protected function getUniName(){//获得唯一的文件名
return md5(uniqid(microtime(true),true));
}
protected function checkUploadPath()//验证上传到的文件夹是否存在,不存在就创建一个
{if (!file_exists($this->uploadPath)){
mkdir($this->uploadPath,0777,true);
}
}
protected function showError(){//显示错误
exit('<span style="color:red">'.$this->error.'</span>');
}
public function uploadFile(){
if($this->checkError()&&$this->checkSize()&&$this->checkExt()&&$this->checkMime()&&$this->checkTrueImg()&&$this->checkHTTPPost()){
$this->checkUploadPath();
$this->uniName=$this->getUniName();
$this->destination=$this->uploadPath.'/'.$this->uniName.'.'.$this->ext;
if(@move_uploaded_file($this->file['tmp_name'], $this->destination)){
return $this->destination;
}else{
$this->error='文件移动失败';
$this->showError();
}
}else{
$this->showError();
}
}
}
php图片上传类
最新推荐文章于 2024-09-10 08:26:51 发布