php实现多文件上传
多文件上传的基本实现
使用HTML表单和PHP处理文件上传是实现多文件上传的基础方法。HTML表单需要设置enctype="multipart/form-data"属性,并包含multiple属性的文件输入字段。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload">
</form>
PHP端通过$_FILES超全局数组接收上传的文件。每个文件包含name、type、tmp_name、error和size信息。
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$uploadDir = 'uploads/';
foreach ($_FILES['files']['tmp_name'] as $key => $tmpName) {
$fileName = basename($_FILES['files']['name'][$key]);
$targetPath = $uploadDir . $fileName;
move_uploaded_file($tmpName, $targetPath);
}
}
文件验证与安全性处理
确保上传文件的安全性至关重要。验证文件类型、大小和检查上传错误是必要的步骤。
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
$maxSize = 2 * 1024 * 1024; // 2MB
foreach ($_FILES['files']['tmp_name'] as $key => $tmpName) {
$fileType = $_FILES['files']['type'][$key];
$fileSize = $_FILES['files']['size'][$key];
$error = $_FILES['files']['error'][$key];
if ($error !== UPLOAD_ERR_OK) {
continue;
}
if (!in_array($fileType, $allowedTypes) || $fileSize > $maxSize) {
continue;
}
// 处理文件上传
}
生成唯一文件名
为避免文件名冲突和安全问题,可以为上传的文件生成唯一名称。
$extension = pathinfo($_FILES['files']['name'][$key], PATHINFO_EXTENSION);
$uniqueName = uniqid() . '.' . $extension;
$targetPath = $uploadDir . $uniqueName;
错误处理与用户反馈
提供清晰的错误信息有助于用户理解上传过程中出现的问题。
$uploadErrors = [
UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize directive in php.ini',
UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE directive in HTML form',
UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
UPLOAD_ERR_NO_FILE => 'No file was uploaded',
UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload'
];
if ($error !== UPLOAD_ERR_OK) {
echo $uploadErrors[$error];
continue;
}
批量上传进度显示
对于大量文件上传,显示上传进度可以改善用户体验。
session_start();
$_SESSION['upload_progress'] = [
'total' => count($_FILES['files']['name']),
'current' => 0
];
foreach ($_FILES['files']['tmp_name'] as $key => $tmpName) {
// 处理上传
$_SESSION['upload_progress']['current']++;
}
前端可以通过AJAX定期查询$_SESSION['upload_progress']来更新进度条。







