1、文件上传原理
将客户端的文件上传到服务器,再将服务器的临时文件上传到指定目录
2、客户端配置
3、服务器端配置
4、错误信息说明
5、客户端限制
<input type='hidden' name='MAX_FILE_SIZE' VALUE='字节数' />
<input type='file' name='myFile' accept='文件的MIME类型' />
6、在客户端的限制,用户可在网页上修改代码后上传,故无实际意义。应在服务器端加以限制
7、完整代码如下:
upload.php
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>文件上传</title>
5 <meta charset="utf-8">
6 </head>
7 <body>
8 <form action="test.php" method="post" enctype="multipart/form-data" >
9 请选择要上传的文件:
10 <input type="file" name="myFile" /><br />
11 <input type="submit" value="上传文件" />
12 </form>
13 </body>
14 </html>
test.php
1 <?php
2 header('content-type:text/html;charset=utf-8');
3 include_once 'upload.func.php';
4 //上传封装函数的五个参数:$fileInfo,$maxsize,$uploadPath,$allowExt,$flag
5 $fileInfo=$_FILES['myFile'];
6 // print_r($_FILES);
7 // exit;
8 // $filename=$_FILES['myFile']['name'];
9 // $type=$_FILES['myFile']['type'];
10 // $tmp_name=$_FILES['myFile']['tmp_name'];
11 // $size=$_FILES['myFile']['size'];
12 // $error=$_FILES['myFile']['error'];
13 $maxsize=2097152;
14 $uploadPath='uploads';
15 $allowExt=array('jpeg','jpg','png','gif');
16 $flag=true;
17 $newName=uploadFile($fileInfo,$maxsize,$uploadPath,$allowExt,$flag);
18 echo "上传成功,路径为:".$newName;
19 ?>
upload.func.php
1 <?php
2 function uploadFile($fileInfo,$maxsize,$uploadPath,$allowExt,$flag){
3 //判断错误号
4 if($fileInfo['error']>0){
5 switch ($fileInfo['error']){
6 case '1':
7 $mes="上传文件超过了PHP配置文件中upload_max_filesize选项的值";
8 break;
9 case '2':
10 $mes="超过了表单MAX_FILE_SIZE限制的大小";
11 break;
12 case '3':
13 $mes="文件部分被上传";
14 break;
15 case '4':
16 $mes="没有选择上传文件";
17 break;
18 case '6':
19 $mes="没有找到临时目录";
20 break;
21 case '7':
22 case '8':
23 $mes="系统错误";
24 break;
25 }
26 exit($mes);
27 }
28 $ext=pathinfo($fileInfo['name'],PATHINFO_EXTENSION);
29 //检测上传文件的类型
30 if (!@in_array($ext,$allowExt)) {
31 exit('非法文件类型');
32 }
33 //检测上传文件的大小是否符合规范
34 //$maxsize=2097152;//默认值为2M
35 if ($fileInfo['size']>$maxsize) {
36 exit('上传文件超过'.($maxsize/1024/1024).'M');
37 }
38 //检测图片是否为真实图片类型,立flag,若不需要检测,则设置flag为false即可
39 //$flag=true;
40 if($flag){
41 if (!@getimagesize($fileInfo['tmp_name'])) {
42 exit('不是真实的图片类型');
43 }
44 }
45 //检测文件是否通过HTTP POST方式上传的
46 if (!@is_uploaded_file($fileInfo['tmp_name'])) {
47 exit('文件不是通过HTTP POST方式上传的');
48 }
49 //存储目录
51 if(!@file_exists($uploadPath)){
52 mkdir($uploadPath,0777,true);
53 chmod($uploadPath,0777);
54 }
55 $uniName=MD5(uniqid(microtime(true),true)).'.'.$ext;
56 $destination=$uploadPath.'/'.$uniName;
57 if (!@move_uploaded_file($fileInfo['tmp_name'], $destination)) {
58 exit('文件上传失败');
59 }
60 //echo "文件上传成功";
61 // return array{
62 // 'newName'=>$destination;
63 // 'size'=>$fileInfo['size'];
64 // 'type'=>$fileInfo['type']
65 // };
66 return $destination;
67 }
68 ?>
如对本文有疑问, 点击进行留言回复!!
网友评论