PHP 同时上传多个文件是指在一个 HTML 表单中允许用户选择并上传多个文件到服务器。这通常通过 HTML 的 <input type="file" multiple>
元素实现。服务器端的 PHP 脚本会处理这些文件,并将它们保存到服务器上。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Multiple File Upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload">
</form>
</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["files"]["name"][0]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// 检查是否真的是一个文件
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["files"]["tmp_name"][0]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// 检查文件是否已经存在
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// 检查文件大小
if ($_FILES["files"]["size"][0] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// 允许特定文件格式
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 检查 $uploadOk 是否设置为 0 通过前面的验证
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// 如果一切正常,尝试上传文件
} else {
if (move_uploaded_file($_FILES["files"]["tmp_name"][0], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["files"]["name"][0])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
原因:客户端或服务器端的文件大小限制。
解决方法:
enctype="multipart/form-data"
是否正确设置。php.ini
中的 upload_max_filesize
和 post_max_size
参数,增加允许上传的文件大小。upload_max_filesize = 10M
post_max_size = 10M
原因:服务器端对文件类型进行了限制。
解决方法:
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "pdf") {
echo "Sorry, only JPG, JPEG, PNG, GIF & PDF files are allowed.";
$uploadOk = 0;
}
原因:目标文件已经存在于服务器上。
解决方法:
if (file_exists($target_file)) {
$new_filename = $target_dir . time() . "_" . basename($_FILES["files"]["name"][0]);
$target_file = $new_filename;
}
通过以上信息,您应该能够理解 PHP 同时上传多个文件的基础概念、优势、类型、应用场景以及常见问题的解决方法。
领取专属 10元无门槛券
手把手带您无忧上云