php 文件上传类
/* 文件上传需要哪些操作 :
* 判断上传过程是否有错误
* 验证上传文件类型是否符合要求
* 验证上传文件大小是否符合要求
* 判断上传路径和上传成功后保存文件的新名称
* 将图片从垃圾目录中移出
*/
Upload.class.php :
class Upload{ //成员属性 public $pic; // 表单名称 public $path;//保存路径 public $size;//文件大小 public $type;//文件类型 public $newImg;// 图片名称 public $pathInfo = array(); //返回的信息 //构造方法 function __construct($pic,$path='./upload',$size=500000,array $type=array('image/jpeg','image/png','image/gif')) { //初始化赋值 $this->pic=$pic; $this->path=rtrim($path,'/').'/'; $this->size=$size; $this->type=$type; } //定义上传方法,所有上传验证都在此方法中实现 public function do_upload(){ //需要将文件上传的5步骤 都执行一遍判断是否成功 if($this->fileError() !==true){ return $this->fileError(); }elseif($this->patternType() !== true){ return $this->patternType(); }elseif($this->pattrenSize() !== true){ return $this->pattrenSize(); }elseif($this->renameImg() !== true){ return $this->renameImg(); }else{ return $this->moveImg(); } } //判断上传过程是否有错误 protected function fileError(){ if($_FILES[$this->pic]['error']>0){ switch ($_FILES[$this->pic]['error']){ case 1: return '超出了php.ini配置文件中upload_max_filesize设置的值'; case 2: return '超过了html表单中设置的MAX_FILE_SIZE的值'; case 3: return '只有部分文件被上传'; case 4: return '没有文件上传'; case 6: return '找不到临时目录'; case 7: return '文件写入失败'; } } return true; } //验证上传文件类型是否符合要求 protected function patternType(){ if(!in_array($_FILES[$this->pic]['type'],$this->type)){ return '图片类型不符合'; } return true; } //验证上传文件大小是否符合要求 protected function pattrenSize(){ if($_FILES[$this->pic]['size'] > $this->size){ return '上传文件大小超过了预设的'.$this->size.'byte'; } return true; } //判断上传路径和上传成功后保存文件的新名称 protected function renameImg(){ //创建路径 if(!file_exists($this->path)){ mkdir($this->path); } //获取图片的后缀名 $suffix = strchr($_FILES[$this->pic]['name'],'.'); //判断名称是否重复 do { $this->newImg = md5(time().mt_rand(1,1000).uniqid()).$suffix; }while(file_exists($this->path.$this->newImg)); return true; } //将图片从垃圾目录中移出 protected function moveImg(){ if(move_uploaded_file($_FILES[$this->pic]['tmp_name'],$this->path.$this->newImg)){ $this->pathInfo['pathinfo'] = $this->path.$this->newImg; $this->pathInfo['name'] = $this->newImg; $this->pathInfo['path'] = $this->path; return $this->pathInfo; }else{ return '未知错误,请重新上传'; } } }
测试
upload.php
<?php include ('Upload.class.php'); $upload = new Upload('pic'); $result=$upload->do_upload(); if(is_array($result)){ var_dump($result); }else{ echo '上传失败'.$result; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="pic"> <input type="submit" value="提交"> </form> </body> </html>
下一篇:使用PHP动态创建嵌套文件夹