2018.09.03
只有一个文件,代码如下:
目录结构:
upfile(文件夹)
├─upfile.html 前端页面
├─upfile.php 后台上传文件
upfile.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<title>文件上传</title>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
</head>
<body>
<form action="upfile.php" method="post" enctype="multipart/form-data">
<label>上传文件:</label>
<input type="file" name="myfile">
<br/>
<input type="submit" value="提交">
</form>
</body>
</html>
upfile.php:
<?php
//判断文件上传错误
switch($_FILES['myfile']['error']){
case 1:
exit('文件超过php.ini限制');
break;
case 2:
exit('文件超过html限制');
break;
case 3:
exit('文件只有部分被上传');
break;
case 4:
exit('没有文件被上传');
break;
case 6:
exit('找不到临时文件夹');
break;
case 7:
exit('文件写入失败');
break;
}
//定义允许上传的文件大小
$maxsize = 1024*1024*2;
if($_FILES['myfile']['size'] > $maxsize){
exit('文件过大,不允许上传!');
}
//定义允许用户上传的文件类型
$mine = ['image/jpeg', 'image/jpg', 'image/pjpeg', 'image/png', 'image/gif'];
//判断用户上传的文件类型是否合法
if(!in_array($_FILES['myfile']['type'],$mine)){
exit('文件类型不合法!');
}
$tmp = $_FILES['myfile']['tmp_name'];
$path = 'e:/wamp64/www/2018/201807/upfiles';
$fileName = getRandName();
//获取文件的扩展名
$ext = pathinfo($_FILES['myfile']['name'], PATHINFO_EXTENSION);
//拼接文件名
$basename = $fileName.'.'.$ext;
//拼接路径
$dest = $path.'/'.$basename;
//将临时文件夹中的文件,移动到指定位置
move_uploaded_file($tmp, $dest);
echo '上传成功,<a href="./upfile.html">返回</a>';
//生成随机文件名
function getRandName(){
$string = date('YmdHis');
for($i=0; $i<6; $i++){
switch(mt_rand(0,2)){
case 0:
$string .= chr(mt_rand(97,122));
break;
case 1:
$string .= chr(mt_rand(65,90));
break;
case 2:
$string .= mt_rand(0,9);
break;
}
}
return $string;
}
网友评论