跟着百度学PHP[13]-文件处理 文件后缀验证、设置随机文件名....
目录:
文件的处理:00x1 判断错误
文件的处理:00x2 判断类型
文件的处理:00x3 文件大小
++++++++++++++++++++++++++++++++++++++++++++++++
文件的处理:00x1 判断错误
既然是上传就会有错误,比如如下图所示的错误:
<?php
header("content-type:text/html;charset=utf-8");
echo "<pre>";
print_r($_FILES);
$tem_file = $_FILES['pic']['tmp_name'];#临时路径
$new_file = "./uploads/".$_FILES['pic']['name'];#要移动的路径。
switch ($_FILES['pic']['error']) {
case 1:
echo "上传的文件超出了限定的值。";
break;
case 2:
echo "上传的文件超出了HTML表单中隐藏域MAX_FILE_SIZE元素所定的最大值。";
break;
case 3:
echo "文件只被不分上传。";
break;
case 4:
echo "没有上传任何文件。";
break;
}
if(move_uploaded_file($tem_file,$new_file)){//如果移动成功就输出上传成功,否则失败
echo "成功上传";
}else{
echo "上传失败";
}
echo "</pre>";
?>
文件的处理:00x2 判断类型
扣出后缀的方法:
<?php $filename = "./def.txt"; $a = (explode(".",basename($filename)));#basename是取出文件名,explode是将文件名打散成为数组。 echo array_pop($a);#array_pop ?>
限制上传的文件类型
<?php $x = "./def.txt"; $a = explode(".",basename($x)); $b = array_pop($a); echo $b;//获取到上传的文件后缀。 $c = array("txt","doc","jpg","swf","rar","zip"); if(!in_array($c,$b)){ echo "<script>alert('抱歉,您上传的文件格式不对。')</script>"; exit; }else{ echo "格式正确,正在上传..."; } ?>
文件的处理:00x3 随机文件名
$new_file = "./uploads/".date('ymdhis').rand(100,999).".".$houzhui;
最终代码:
前端:
<html> <body> <form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000"> uplaod file:<input type="file" name="pic" value=""> <input type="submit" value="uplaod" name="pic"> </form> </body> </html>
后端:
<?php header("content-type:text/html;charset=utf-8"); echo "<pre>"; print_r($_FILES); $maxfile = "1000000"; $hello = explode(".",basename($_FILES['pic']['name'])); $houzhui = array_pop($hello); $b = array("jpg","doc","txt","zip"); if (!in_array($houzhui,$b)) { echo "<script>alert('你上传的文件类型错误')</script>"; exit; } if ($_FILES['pic']['size'] > $maxfile){ echo "<script>alert('文件超出了限制')</script>"; exit; } //------------------------随机文件名------------------------- $tem_file = $_FILES['pic']['tmp_name'];#临时路径 $new_file = "./uploads/".date('ymdhis').rand(100,999).".".$houzhui;#要移动的路径。 switch ($_FILES['pic']['error']) { case 1: echo "上传的文件超出了限定的值。"; break; case 2: echo "上传的文件超出了HTML表单中隐藏域MAX_FILE_SIZE元素所定的最大值。"; break; case 3: echo "文件只被不分上传。"; break; case 4: echo "没有上传任何文件。"; break; } if(move_uploaded_file($tem_file,$new_file)){//如果移动成功就输出上传成功,否则失败 echo "成功上传"; }else{ echo "上传失败"; } echo "</pre>"; ?>
By:珍惜少年时博客:http://www.cnblogs.com/xishaonian/
*-------------------------------------------*