php实现多文件上传的简单方法,需要的朋友可以参考学习。
下面我们再通过具体的代码示例,为大家详细介绍php使用multiple属性来实现多文件上传及其信息解析的完整方法。
首先HTML form表单代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="getFile.php" method="post" enctype="multipart/form-data">
选择文件进行上传:<input type="file" name="file[]" multiple=""><br>
<input type="submit" value="上传">
</form>
</body>
</html>
var_dump($_FILES);
<?php
/**
* 组装多文件上传信息
*/
$files = [];
function getFile()
{
$i = 0;
foreach ($_FILES as $file) {
if (is_string($file['name'])) {
$files['$i'] = $file;
$i++;
} elseif (is_array($file['name'])) {
foreach ($file['name'] as $k => $v) {
$files[$i]['name'] = $file['name'][$k];
$files[$i]['type'] = $file['type'][$k];
$files[$i]['tmp_name'] = $file['tmp_name'][$k];
$files[$i]['error'] = $file['error'][$k];
$files[$i]['size'] = $file['size'][$k];
$i++;
}
}
}
return $files;
}
/**
* 文件上传
* @param $fileInfo
* @param string $upload
* @param array $imagesExt
* @return string
*/
function upload_file($fileInfo, $upload = "./upload", $imagesExt = ['gif', 'png', 'jpg'])
{
$res = [];
if ($fileInfo['error'] === 0) {
$ext = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $imagesExt)) {
$res['mes'] = "文件非法类型";
}
if (!is_dir($upload)) {
mkdir($upload, 0777, true);
}
if ($res) {
return $res;
}
$fileName = md5(uniqid(microtime(true), true)) . "." . $ext;
$destName = $upload . "/" . $fileName;
if (!move_uploaded_file($fileInfo['tmp_name'], $destName)) {
$res['mes'] = "文件上传失败!";
}
$res['mes'] = $fileInfo['name'] . "文件上传成功!";
$res['dest'] = $destName;
return $res;
} else {
switch ($fileInfo['error']) {
case 1:
$res['mes'] = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
break;
case 2:
$res['mes'] = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
break;
case 3:
$res['mes'] = '文件只有部分被上传';
break;
case 4:
$res['mes'] = '没有文件被上传';
break;
case 6:
$res['mes'] = '找不到临时文件夹';
break;
case 7:
$res['mes'] = '文件写入失败';
break;
}
return $res;
}
}
$files = getFile();
foreach ($files as $fileInfo) {
$res = upload_file($fileInfo);
echo $res['mes'];
var_dump($res['dest']);
在上述代码中,我们首先通过foreach循环判断语句对上传来的多维数组信息进行判断重组,然后再创建upload_file方法对多个文件的上传信息进行解析。
这里的upload_file方法我们在【PHP文件上传方法详解及其信息解析】这篇文章中已经详细介绍过了,大家可以选择参考。以上就是关于PHP实现多文件上传及其信息解析的具体方法。