檔案上傳是 Web 應用常見功能,但也是高風險攻擊面。本文完整涵蓋 HTML 表單設定、$_FILES 結構解析、安全驗證策略、move_uploaded_file() 正確用法、儲存最佳實務與進階防護。
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">選擇檔案:</label>
<input type="file" name="file" id="file" accept="image/*" />
<input type="submit" name="submit" value="上傳" />
</form>
method="post":檔案上傳必須用 POSTenctype="multipart/form-data":必須,否則 $_FILES 為空type="file":瀏覽器顯示檔案選擇對話框<?php
// 單一檔案上傳
$_FILES['file'] = [
'name' => 'photo.jpg', // 用戶端原始檔名
'type' => 'image/jpeg', // 瀏覽器回報 MIME 類型(不可信)
'tmp_name' => '/tmp/phpA1B2C3', // 伺服器暫存檔路徑(關鍵)
'error' => UPLOAD_ERR_OK, // 錯誤代碼(0 成功)
'size' => 102400, // 檔案大小(位元組)
'full_path' => 'photo.jpg', // 完整路徑(PHP 8.1+,目錄上傳時)
];
?>
| 常數 | 值 | 說明 |
|---|---|---|
UPLOAD_ERR_OK | 0 | 上傳成功 |
UPLOAD_ERR_INI_SIZE | 1 | 超過 upload_max_filesize (php.ini) |
UPLOAD_ERR_FORM_SIZE | 2 | 超過表單 MAX_FILE_SIZE 隱藏欄位 |
UPLOAD_ERR_PARTIAL | 3 | 部分上傳(網路中斷) |
UPLOAD_ERR_NO_FILE | 4 | 未選擇檔案 |
UPLOAD_ERR_NO_TMP_DIR | 6 | 缺少暫存目錄 |
UPLOAD_ERR_CANT_WRITE | 7 | 寫入磁碟失敗 |
UPLOAD_ERR_EXTENSION | 8 | PHP 擴展阻止上傳 |
<?php
// upload.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 1. 檢查錯誤
if (($file = $_FILES['file'] ?? null) === null) {
die('未收到檔案');
}
if ($file['error'] !== UPLOAD_ERR_OK) {
die('上傳錯誤代碼:' . $file['error']);
}
// 2. 顯示檔案資訊
echo "檔名:{$file['name']}<br>";
echo "類型:{$file['type']}<br>";
echo "大小:" . ($file['size'] / 1024) . " KB<br>";
echo "暫存路徑:{$file['tmp_name']}<br>";
}
?>
name、type、size 皆可偽造)。必須在伺服器端重新驗證。
<?php
$allowedMimes = [
'image/jpeg' => '.jpg',
'image/png' => '.png',
'image/gif' => '.gif',
'image/webp' => '.webp',
];
$mime = $file['type']; // 瀏覽器提供,僅作初步篩選
if (!isset($allowedMimes[$mime])) {
die('不允許的檔案類型');
}
$ext = $allowedMimes[$mime];
?>
<?php
// 使用 finfo 讀取檔案魔數判斷真實類型
$finfo = new finfo(FILEINFO_MIME_TYPE);
$realMime = $finfo->file($file['tmp_name']);
if (!isset($allowedMimes[$realMime])) {
die('檔案內容類型不符:' . $realMime);
}
$ext = $allowedMimes[$realMime];
// 額外:檢查圖片完整性
$imgInfo = @getimagesize($file['tmp_name']);
if ($imgInfo === false) {
die('非有效圖片檔案');
}
// $imgInfo[0]=寬, [1]=高, [2]=類型常數, [3]=width/height 字串
?>
<?php
const MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
const MAX_WIDTH = 1920;
const MAX_HEIGHT = 1080;
if ($file['size'] > MAX_FILE_SIZE) {
die('檔案過大,限制 2MB');
}
if ($imgInfo[0] > MAX_WIDTH || $imgInfo[1] > MAX_HEIGHT) {
die("圖片尺寸超過限制 ({$MAX_WIDTH}x{$MAX_HEIGHT})");
}
?>
<?php
// 目標目錄(建議置於 Web 根目錄外部)
$uploadDir = __DIR__ . '/../storage/uploads/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// 產生安全檔名:隨機 + 正確副檔名
$safeName = bin2hex(random_bytes(16)) . $ext;
$destPath = $uploadDir . $safeName;
// 移動暫存檔到永久位置
if (move_uploaded_file($file['tmp_name'], $destPath)) {
// 成功:設定適當權限
chmod($destPath, 0644);
// 記錄資料庫
// $db->insert('uploads', ['original_name'=>$file['name'], 'stored_name'=>$safeName, 'mime'=>$realMime, 'size'=>$file['size']]);
echo "上傳成功:$safeName";
} else {
die('檔案儲存失敗');
}
?>
# Apache .htaccess (上傳目錄放置)
<FilesMatch "\.(php|phtml|php3|php4|php5|php7|phar|pl|cgi)$">
Require all denied
</FilesMatch>
# 或 Nginx
location /uploads/ {
location ~ \.php$ { return 403; }
}
<?php
// 使用 GD 或 ImageMagick 重新編碼,徹底清除潛在惡意內容
$image = imagecreatefromstring(file_get_contents($destPath));
if ($image) {
imagejpeg($image, $destPath, 85); // 重新壓縮儲存
imagedestroy($image);
}
?>
<?php
// 生產環境建議整合
$scanResult = shell_exec("clamscan --no-summary " . escapeshellarg($destPath));
if (strpos($scanResult, 'FOUND') !== false) {
unlink($destPath);
die('檔案包含惡意軟體');
}
?>
Content-Disposition: attachment 強制下載<input type="file" name="files[]" multiple />
<?php
foreach ($_FILES['files']['tmp_name'] as $index => $tmpName) {
$error = $_FILES['files']['error'][$index];
if ($error !== UPLOAD_ERR_OK) continue;
$name = $_FILES['files']['name'][$index];
$size = $_FILES['files']['size'][$index];
// 單檔處理邏輯...
}
?>