单文件长传
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文优化件上传</title>
</head>
<body>
<form method="post" action="3.file.php" enctype="multipart/form-data">
<input type="file" name="pic" />
<input type="submit" name="btn" value="上传" />
</form>
</body>
</html>
PHP
<?php
/**
* @param bool isset() 判断是否设置
* @param bool $error 1,2,3,4,6,7错误号|0正确
* @param array $allow 验证格式
* @param resource finfo_open 创建filefinfo资源
* @param resource $type 文件类型
* @param bool in_array 检查数组中是否存在某个值
* @param bool $_FILES['pic']['pic'] 验证大小
* @param string number_format 以千分一的情况下格式化一个数字
* @param bool is_uploaded_file 判断是否是http上传
* @param string uniqid 生成唯一ID
* @param sting strrchr 从右面开始截取字符串
* @return [type] [<description>]
* @author 小朱
*/
if(isset($_POST['btn'])){
$error = $_FILES['pic']['error'];
if ($error != 0) {
switch ($error) {
case 1:
echo "文件超出了php.ini允许的范围";
break;
case 2:
echo "文件超出了表单允许的范围";
break;
case 3:
echo "只有部分文件上传";
break;
case 4:
echo "没有上传文件";
break;
case 6:
echo "找不到临时文件";
break;
case 7:
echo "文件写入失败";
break;
default:
echo "未知错误";
break;
}
exit;
}
$allow = array('image/png','image/jpeg','image/gif');
$info = finfo_open(FILEINFO_MIME_TYPE);
$type = finfo_file($info, $_FILES['pic']['tmp_name']);
if (!in_array($type,$allow)) {
echo "文件格式不正确,只允许上传".implode(',', $allow);
exit;
}
$max_size = 100000;
if ($_FILES['pic']['size'] > $max_size) {
echo "文件不能超过".number_format($max_size/1024,1).'k';
exit;
}
if (!is_uploaded_file($_FILES['pic']['tmp_name'])) {
echo "文件不是http上传";
exit;
}
$path = './uploads/'.uniqid().strrchr($_FILES['pic']['name'], '.');
if (move_uploaded_file($_FILES['pic']['tmp_name'], $path)) {
echo "文件上传成功";
}else{
echo "文件上传失败";
}
}
多文件上传
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文优化件上传</title>
</head>
<body>
<form method="post" action="3.file.php" enctype="multipart/form-data">
<input type="file" name="pic[]"/><br/>
<input type="file" name="pic[]"/><br/>
<input type="file" name="pic[]"/><br/>
<input type="submit" name="btn" value="上传" />
</form>
</body>
</html>
PHP
<?php
/**
* @param bool isset 判断是否为空
* @param $tmp_path 临时文件
* @param $dsn_path 目标路径
* @param bool move_uploaded_file 文件上传
* @param string uniqid('',true) 生成多个唯一ID
* @param string strrchr 从右面开始截取的字符串
* @return
* @author
*/
if(isset($_POST['btn'])){
foreach($_FILES['pic']['name'] as $k=>$name){
$tmp_path = $_FILES['pic']['tmp_name'][$k];
$dsn_path = './uploads/'.uniqid('',true).strrchr($name,'.');
move_uploaded_file($tmp_path,$dsn_path);
}
}