文件上传

HTMl文件:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 5 <title>文件上传</title>
 6 </head>
 7 <body>
 8     <form action="upload.php" enctype="multipart/form-data" method="post">
 9         <input type="file" name="image"/>
10         <input type="submit" value="上传"/>
11     </form>
12 
13 </body>
14 </html>

PHP文件:

<?php
header('Content-type:text/html;charset=utf-8');

echo '<pre>';

//接受文件
$file = $_FILES['image'];

//引入文件上传文件
include_once 'upload_fun.php';

//确定允许上传的文件了性
$types = array('image/png','image/jpg','image/gif','image/jpeg','image/pjgeg','image/bmp');

//调用函数
$filename = upload($file,'uploads',$types);

var_dump($filename);

文件上传函数:

 1 <?php
 2 //php文件上传函数
 3 
 4 /*文件上传
 5  * @param1 $file 文件上传的五要素
 6  * @param2 $path 文件上传的路径
 7  * @param3 $mime 允许上传的文件类型
 8  * @return 返回文件上传后的新名字
 9  * 
10  */
11 
12 function upload($file,$path,$mime){
13     //判断上传文件的是否是正确
14     if(!is_array($file)){
15         echo '上传的文件有误!';
16         return ;    //一旦出错不再执行
17     }
18     
19     //判断错误编码,检查是否有错
20     switch ($file['error']){
21         case 1:
22             echo '文件超过服务器允许的大小';
23             return;
24         case 2:
25             echo '文件超过表单允许大小!';
26             return;
27         case 3:
28             echo '文件上传部分!';
29             eturn;
30         case 4:
31             echo '用户没有选择要上传的文件!';
32             return;
33         case 6:
34         case 7:
35             echo '服务器错误!';
36             return;
37         
38     }
39     
40     //判断用户上传的文件类型是否正确,使用类型判断
41     if (!in_array($file['type'], $mime)) {
42         //该文件类型不存在
43         echo '不支持上传当前文件类型';
44         return;
45     }
46     
47     //移动文件并获取新的名字
48     $newname = getRandomName($file['type']);
49     if(move_uploaded_file($file['tmp_name'], $path.'/'.$newname)){
50         //成功:返回新的文件名字
51         return $newname;
52     }else{
53         //失败
54         echo '文件移动失败';
55         return;
56     }
57     
58 }
59 
60 //定义一个函数用于生产新的文件名字
61 function getRandomName($type){
62     //生成时间部分
63     $name = date('YmdHis');
64     
65     //随机生成六位字符串
66     $str = 'abcdefghijhlmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
67     
68     for($i = 0;$i < 6;$i++){
69         $name .=$str[mt_rand(0,strlen($str))-1];
70     }
71     
72     $name .= '.'.substr($type, strpos($type, '/')+1);
73     
74     //返回新的随机名字
75     return $name;
76 }

 

posted @ 2015-10-04 12:55  lesuso  阅读(118)  评论(0编辑  收藏  举报