php文件上传之单文件上传

为了简单一些,php文件跟form表单写在了一个文件里.

php单文件上传---->

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="UTF-8" />
 5 </head>
 6 <body>
 7 <form action="upload.php" method="post" enctype="multipart/form-data">
 8     请选择要上传的文件:<input type="file" name="myfile"/><br /><br />
 9     <input type="submit" value="submit" />
10     <input type="hidden" name="MAX_FILE_SIZE" value="5982"/>
11 </form>
12 </body>
13 </html>
14 
15 
16 
17 <?php
18     if(!empty($_FILES)){
19         header('content-type:text/html;charset=utf-8');
20         $fileInfo=$_FILES['myfile'];
21         print_r($_FILES);
22         //如果上传出错则退出并打印错误信息
23         if($fileInfo['error']>0){
24             switch($fileInfo['error']){
25                 case 1:
26                     $msg_error='上传文件超过了php配置文件中UPLOAD_MAX_FILESIZE选项的值';
27                     break;
28                 case 2:
29                     $msg_error='超过了表单MAX_FILE_SIZE限制的大小';
30                     break;
31                 case 3:
32                     $msg_error='文件部分上传';
33                     break;
34                 case 4:
35                     $msg_error='没有文件上传';
36                     break;
37                 case 6:
38                     $msg_error='没有找到临时目录';
39                     break;
40                 case 7:
41                 case 8:
42                     $msg_error='系统错误';
43                     break;
44             }
45             exit($msg_error);
46         }
47         $filename=$fileInfo['name'];
48         //获取文件的扩展名
49         $ext=strtolower(substr($filename,strrpos($filename,'.')+1));
50         //定义可允许上传的扩展名
51         $allowExt=array('txt','html','png','gif','jpeg');
52         //检测上传文件的类型
53         if(!in_array($ext,$allowExt)){
54             exit('上传文件类型错误');
55         }
56 
57 
58        //检测文件的大小
59         $maxSize=2097152;
60         if($fileInfo['size']>$maxSize){
61             exit('上传文件过大');
62         }
63 
64         //检测是否为HTTP POST方式上传上来的
65         if(!is_uploaded_file($fileInfo['tmp_name'])){
66             exit('文件不是通过HTTP POST方式提交上来的');
67         }
68 
69         //确保文件名字唯一,防止同名文件被覆盖
70         $uniqName=md5(uniqid(microtime(true),true)).'.'.$ext;
71 
72         //定义保存在哪个文件夹下,如果没有该文件夹则创建
73         $path='uploads';
74         if(!file_exists($path)){
75             mkdir($path,0777,true);
76             chmod($path,0777);
77         }
78         $destination=$path.'/'.$uniqName;
79 
80         //移动文件至要保存的目录
81         if(! @move_uploaded_file($fileInfo['tmp_name'],$destination)){
82             exit('文件上传失败');
83         }
84 
85         echo '上传成功';
86 
87     }
88 ?>

 

posted @ 2015-07-23 14:02  潘家大少爷  阅读(330)  评论(0编辑  收藏  举报