1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| <?php header("Content-type:text/html;charset=utf-8");
function upload_single($file,$allow_type,$path,&$error,$allow_format = array(),$max_size = 2000000){ if(!is_array($file) || !isset($file['error'])){ $error = '不是一个有效的文件'; return false; } if(!is_dir($path)){ $error = '文件存储路径不存在'; return false; } switch ($file['error']) { case 1: case 2: $error = '文件超出预设值'; return false; case 3: $error = '文件上传过程出错'; return false; case 4: $error = '没有选中要上传的文件'; return false; case 6: case 7: $error = '文件保存失败'; return false; } if(!in_array($file['type'],$allow_type)){ $error = '请上传正确的文件类型'; return false; } $ext = ltrim(strrchr($file['name'],'.'),'.'); if(!empty($allow_format) && !in_array($ext,$allow_format)){ $error = '请上传正确的文件类型'; return false; } if($file['size'] > $max_size){ $error = '当前文件超出大小,请不要大于' . $max_size . '字节'; } if(!is_uploaded_file($file['tmp_name'])){ $error = '错误,不是上传文件'; return false; } $fullname = strstr($file['type'],'/',true) . date('Ymd') . mt_rand(10000,99999) . '.' .$ext; if(move_uploaded_file($file['tmp_name'],$path . '/' . $fullname)){ return $fullname; }else{ $error = '文件上传失败'; return false; } }
$file = $_FILES['img']; $path = 'upload'; $allow_type = array('image/jpg','image/jpeg'); $allow_format = array('jpg','jpeg','JPG','JPEG'); $max_size = 1048576;
if($filename = upload_single($file,$allow_type,$path,$error,$allow_format,$max_size)){ echo $filename; }else{ echo $error; }
|