使用 $_FILES['imgfile']['name'][$i] 數組結構遍歷處理每個文件。
<?php
$img_dir = "../upload/"; // 上傳目錄(需寫權限)
// 初始化統計
$uploaded = 0;
$unuploaded = 0;
$result = array();
// 遍歷最多 5 個文件
for ($i = 0; $i <= 5; $i++) {
$is_file = $_FILES['imgfile']['name'][$i];
if (empty($is_file)) continue;
$result[$i] = "<tr class='td2' align='center'>
<td>{$_FILES['imgfile']['name'][$i]}</td>
<td>" . round($_FILES['imgfile']['size'][$i]/1024, 2) . "K</td>
<td>{$_FILES['imgfile']['type'][$i]}</td>
<td>";
// 類型白名單驗證
$allowedTypes = array(
'image/pjpeg', // JPG (IE)
'image/jpeg', // JPG (標準)
'image/gif',
'image/png',
'image/x-png', // PNG (IE)
'image/bmp'
);
if (in_array($_FILES['imgfile']['type'][$i], $allowedTypes)) {
// 重名檢測
$targetPath = $img_dir . $_FILES['imgfile']['name'][$i];
if (!file_exists($targetPath)) {
if (move_uploaded_file($_FILES['imgfile']['tmp_name'][$i], $targetPath)) {
$result[$i] .= "成功";
$uploaded++;
} else {
$result[$i] .= "<font color='red'>移動失敗</font>";
$unuploaded++;
}
} else {
$result[$i] .= "<font color='red'>文件已存在</font>";
$unuploaded++;
}
} else {
$result[$i] .= "<font color='red'>類型不允許</font>";
$unuploaded++;
}
$result[$i] .= "</td></tr>";
}
// 空提交檢查
if (empty($result)) {
die("錯誤:未選擇任何圖片");
}
// 輸出結果表格
echo "<table cellpadding=4 cellspacing=1 border=0 class=table width=400 align=left>
<tr class=navi align=center>
<td>文件名</td><td>大小</td><td>類型</td><td>上傳結果</td>
</tr>";
foreach ($result as $value) echo $value;
echo "<tr class=td1>
<td colspan=4>共上傳 " . ($uploaded + $unuploaded) . ", 成功: $uploaded, 失敗:<font color=red> $unuploaded</font> </td>
</tr>
<tr class=navi>
<td colspan=4 align=center>[ <a href='uploadimg.php?action=upload'>繼續上傳</a> ] [ <a href='image.php'>瀏覽圖片</a> ]</td>
</tr>
</table>";
?>
getimagesize() 驗證真實圖片頭)uniqid() . '.' . pathinfo($name, PATHINFO_EXTENSION) 避免重名與惡意文件名php_flag engine off)php.ini upload_max_filesize + 代碼層二次檢查<form action="uploadimg.php" method="post" enctype="multipart/form-data">
<input type="file" name="imgfile[]" /><br>
<input type="file" name="imgfile[]" /><br>
<input type="file" name="imgfile[]" /><br>
<input type="file" name="imgfile[]" /><br>
<input type="file" name="imgfile[]" /><br>
<input type="submit" value="上傳" />
</form>