<?php $file = $_FILES[‘img‘]; $obj = new File(); $res = $obj->upload($file,‘upload‘); if($res){ echo $res; }else{ echo File::$error; } //sleep(30); //Array ( [name] => wjdk.png [type] => image/png [tmp_name] => C:\Windows\php955D.tmp [error] => 0 [size] => 668730 ) class File{ //设置属性:保存允许上传的Mime类型 private static $types = array(‘image/jpg‘,‘imgae/jpeg‘,‘image/pjpeg‘,‘image/png‘); //修改允许上传的文件类型 public static function setType($type=array()){ if(!empty($type)){ self::$types = $type; } } public static $error; //记录文件上传过程中出现的错误 //上传方法 public static function upload($file,$path,$max = 2000000){ //判断文件有效性 if(!isset($file[‘error‘]) || count($file) != 5){ self::$error = ‘错误的上传文件‘; return false; } if(!is_dir($path)){ self::$error = ‘文件路径不存在‘; return false; } //判定文件是否正确上传 switch ($file[‘error‘]){ case 1: case 2: self::$error = ‘文件超过服务器允许大小‘; return false; case 3: self::$error = ‘文件只有部分被上传‘; return false; case 4: self::$error = ‘没有选中要上传的文件‘; return false; case 6: self::$error = ‘找不到临时文件夹‘; return false; case 7: self::$error = ‘文件写入失败‘; return false; } //判定文件类型 if(!in_array($file[‘type‘],self::$types)){ self::$error = ‘当前上传的文件类型不允许‘; return false; } //判断文件大小 if($file[‘size‘] > $max){ self::$error = ‘当前上传的文件超过允许的大小,当前允许的大小为‘.string()($max/1024/1024).‘M‘; return false; } $filename = self::getRandomName($file[‘name‘]); if(move_uploaded_file($file[‘tmp_name‘],$path.‘/‘.$filename)){ return $filename; }else{ self::$error = ‘文件移动失败‘; return false; } } public static function getRandomName($filename,$prefix = ‘image‘){ $ext = strrchr($filename,‘.‘); $new_name = $prefix.date(‘YmdHis‘); for($i=0;$i<6;$i++){ $new_name .= chr(mt_rand(65,90)); } return $new_name.$ext; } }