需求:控制上传类型,可选上传后缀,控制上传大小
1、前台代码
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
| <!doctype html> <html lang="ch"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>文件上传</title> </head> <body> 仅允许上传JPG,JPEG,PNG文件 <form method="post" action="index.php" enctype="multipart/form-data"> <input type="file" name="image" /> <input type="submit" value="上传" /> </form> </body> </html> <?php include 'upload.php'; $allow_type = array('image/jpg','image/jpeg','image/png'); $allow_format = array('jpg','jpeg','png'); $path = 'upload'; $error = ''; if (!empty($_FILES['image'])) { $file = $_FILES['image']; $bool = api_upload($file, $allow_type, $path, $error, $allow_format, 1000000); if (!$bool){ echo $error; }else{ echo $bool; } }
|
2、函数代码
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
| <?php
function api_upload($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 = '文件大小超过限制'; return false; }
if (!is_uploaded_file($file['tmp_name'])){ $error = '该文件不是上传文件'; return false; } $name = strstr($file['type'],'/',true) . '_' . (string)time() . '.' . $ext; if (move_uploaded_file($file['tmp_name'],$path. '/' . $name)){ $error = '文件上传成功'; return $path . '/' .$name; }else{ $error = '文件移动失败'; return false; } }
|