在PHP中,要實現多文件上傳,可以通過以下步驟:
$_FILES
超全局變量來處理上傳的文件。這是一個簡單的示例:
HTML表單
<!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">
Select files to upload:
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload">
</form>
</body>
</html>
注意<input>
標簽的name
屬性設置為files[]
,這樣可以接收多個文件。multiple
屬性允許用戶選擇多個文件。
PHP處理腳本 (upload.php)
<?php
// 設置上傳目錄
$target_dir = "uploads/";
// 遍歷所有上傳的文件
for ($i = 0; $i< count($_FILES['files']['name']); $i++) {
// 獲取文件信息
$tmp_name = $_FILES['files']['tmp_name'][$i];
$file_name = $_FILES['files']['name'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_type = $_FILES['files']['type'][$i];
// 檢查文件大小和類型(此處僅為示例,可根據需求修改)
if ($file_size > 5000000) {
echo "Sorry, the file is too large.";
continue;
}
if ($file_type != "image/jpeg" && $file_type != "image/png") {
echo "Sorry, only JPG and PNG files are allowed.";
continue;
}
// 設置目標文件名
$target_file = $target_dir . basename($file_name);
// 檢查文件是否已存在
if (file_exists($target_file)) {
echo "Sorry, the file already exists.";
continue;
}
// 嘗試上傳文件
if (move_uploaded_file($tmp_name, $target_file)) {
echo "The file " . $file_name . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
這個PHP腳本會遍歷所有上傳的文件,檢查文件大小和類型,然后將文件移動到指定的上傳目錄。你可以根據需要修改這個腳本,例如添加更多的驗證或處理其他類型的文件。