1: <?php
2: header("Content-Type:text/html; charset=utf8");
3: // echo "<pre>";
4: // print_r($_FILES);
5: // echo "</pre>";
6:
7: // 1.检查错误:$_FILES['pic']['error']==0
8: if($_FILES['pic']['error']>0)
9: {
10: switch ($_FILES['pic']['error']) {
11: case 1:
12: die("文件超过了 php.ini 中 upload_max_filesize 选项限制的值");
13: case 2:
14: die("文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值");
15: case 3:
16: die("文件只有部分被上传");
17: case 4:
18: die("没有文件被上传");
19: default:
20: die("网络异常");
21: }
22: }
23: // 2.限制上传大小:$_FILES['pic']['size']/1024 小于5M
24: $maxSize = 1024*1024;
25: if($_FILES['pic']['size']>$maxSize)
26: {
27: die("上传失败,上传文件不能超过".($maxSize/1024)."M");
28: }
29:
30: // 3.限制文件扩展名:$_FILES['pic']['type'] 只能是图片
31: // image/gif
32: // image/jpeg
33: // image/png
34:
40:
41: // 通过文件扩展名来限制:
42: //取得文件扩展名
43: $arr = explode('.', $_FILES['pic']['name']);
44: $ext = strtolower($arr[count($arr)-1]);
45:
46: $allowExt=array("png","gif","jpg","jpeg");
47: if(!in_array($ext, $allowExt))
48: {
49: die("上传失败,文件格式不正确!");
50: }
51:
52: // 4.重命名文件(文本文件处理文件内容)
53: $filePath = "";
54: $newName = date('Y').date('m').date('d').date('H').date('i').date('s').rand(100,999).'.'.$ext;
55:
56: // 5.将文件保存到指定目录
57: //判断文件是否是通过HTTP POST上传的文件
58: if(is_uploaded_file($_FILES['pic']['tmp_name'])){
59: if(move_uploaded_file($_FILES['pic']['tmp_name'], "https://www.cnblogs.com/lt-style/p/DownFiles/".$newName)){
60: echo "文件上传成功!";
61: }
62: }
63: else{
64: die("非上传文件");
65: }
66: