参考: http://www.phpchina.com/html/97/14397-4443.html
利用html提供的文件上传功能,php其实仅仅是把它保存在本地指定目录。
1、首先dump php 内置变量:
#var_dump($_FILES);
array(1) {
["file"]=>
array(5) {
["name"]=>
string(8) "test.txt"
["type"]=>
string(10) "text/plain"
["tmp_name"]=>
string(18) "/var/tmp/phpUCf72l"
["error"]=>
int(0)
["size"]=>
int(589)
}
}
可以看到文件其实已经被临时存放在服务器了。
2、这时需要做的,就是把它用合适的名称保存到指定目录。
获取文件后缀,进行一些必要的检查。
生成一个唯一的文件名。
---------------------------------------------
# index.html
<form method="post" action="upload.php" enctype="multipart/form-data">
<table border=0 cellspacing=0 cellpadding=0 align=center width="100%">
<tr>
<td width=55 height=20 align="center"><input type="hidden" name="MAX_FILE_SIZE" value="2000000">文件: </TD>
<td height="16">
<input name="file" type="file" value="浏览" >
<input type="submit" value="上传" name="B1">
</td>
</tr>
</table>
</form>
# upload.php
<?php
//var_dump($_FILES);
$uploaddir = "./files/";//设置文件保存目录 注意包含/
$allow_types = array("txt");//设置允许上传文件的类型
// 返回函数
+ +-- 4 lines: function _return($ret_code, $ret_msg){------------------------------------------------------------------------------
+ +-- 3 lines: function _return_ok($ret_msg){--------------------------------------------------------------------------------------
+ +-- 3 lines: function _return_error($ret_msg){-----------------------------------------------------------------------------------
// 原始文件信息
$raw_file_name = trim($_FILES['file']['name']);
$raw_file_type = trim($_FILES['file']['type']);
$raw_file_tail = strtolower(substr(strrchr($raw_file_name, '.'), 1));
//判断文件类型
if(!in_array($raw_file_tail, $allow_types)){
$text = implode(",",$allow_types);
_return_error("allow type: $text");
}
if ('text/plain' != $raw_file_type){
_return_error("allow type: text/plain");
}
//生成目标文件的文件名
$upload_file_name = tempnam($uploaddir, $raw_file_name.".");
// 保存文件
if (move_uploaded_file($_FILES['file']['tmp_name'],$upload_file_name)){
_return_ok("ok");
} else {
_return_error("fail");
}
exit;
?>
本文介绍如何使用PHP处理HTML表单提交的文件上传请求,包括文件类型的验证、唯一文件名的生成及文件保存的过程。
1万+

被折叠的 条评论
为什么被折叠?



