單檔案上傳是 PHP 入門必學技能。核心函數 move_uploaded_file() 將暫存檔移至目標路徑。本文提供最精簡可用範例,並說明必要的安全檢查。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>單檔案上傳</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
<div class="card shadow" style="max-width: 500px; margin: auto;">
<div class="card-header bg-primary text-white text-center"><h4>檔案上傳</h4></div>
<div class="card-body">
<form action="upload_simple.php" method="post" enctype="multipart/form-data">
<div class="mb-3">
<label class="form-label">選擇檔案</label>
<input type="file" name="file" class="form-control" required>
<div class="form-text">限制:jpg, png, pdf,最大 2MB</div>
</div>
<button type="submit" class="btn btn-primary w-100">上傳</button>
</form>
<div id="msg" class="mt-3"></div>
</div>
</div>
</div>
</body>
</html>
<?php
// upload_simple.php
declare(strict_types=1);
const UPLOAD_DIR = __DIR__ . '/uploads/';
const MAX_SIZE = 2 * 1024 * 1024; // 2MB
const ALLOWED_MIME = ['image/jpeg', 'image/png', 'application/pdf'];
const ALLOWED_EXT = ['jpg', 'jpeg', 'png', 'pdf'];
// 確保目錄存在
if (!is_dir(UPLOAD_DIR)) {
mkdir(UPLOAD_DIR, 0755, true);
}
$response = ['success' => false, 'message' => ''];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
$file = $_FILES['file'];
// 1. 錯誤碼檢查
if ($file['error'] !== UPLOAD_ERR_OK) {
$response['message'] = match ($file['error']) {
UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => '檔案過大',
UPLOAD_ERR_PARTIAL => '上傳中斷',
UPLOAD_ERR_NO_FILE => '未選擇檔案',
default => '上傳錯誤:' . $file['error'],
};
}
// 2. 大小檢查
elseif ($file['size'] > MAX_SIZE) {
$response['message'] = '檔案超過 2MB 限制';
}
// 3. MIME 型別檢查(真實內容)
else {
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, ALLOWED_MIME, true)) {
$response['message'] = '檔案類型不允許(' . $mime . ')';
}
// 4. 副檔名檢查
else {
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ALLOWED_EXT, true)) {
$response['message'] = '副檔名不允許';
}
// 5. 移動檔案
else {
$safeName = date('YmdHis') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
$dest = UPLOAD_DIR . $safeName;
if (move_uploaded_file($file['tmp_name'], $dest)) {
$response['success'] = true;
$response['message'] = '上傳成功!';
$response['file'] = $safeName;
} else {
$response['message'] = '檔案移動失敗(權限問題)';
}
}
}
}
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
| 函數 | 用途 |
|---|---|
move_uploaded_file($src, $dest) | 將 HTTP POST 上傳的暫存檔移動到新位置,成功回傳 true。內建防止偽造上傳檔案的安全檢查。 |
is_uploaded_file($path) | 確認檔案確實為 HTTP POST 上傳(可選,move_uploaded_file 內部已檢查)。 |
finfo::file() | 偵測檔案真實 MIME 型別,防止偽裝副檔名。 |
; php.ini
file_uploads = On
upload_max_filesize = 2M
post_max_size = 8M
max_file_uploads = 20
; 上傳暫存目錄(需可寫)
; upload_tmp_dir = /tmp
| 現象 | 原因 | 解決 |
|---|---|---|
move_uploaded_file() 回傳 false | 目標目錄不可寫、磁碟滿、open_basedir 限制 | 檢查目錄權限 0755、擁有者、磁碟空間、php.ini open_basedir |
| 上傳大檔案失敗 | 超過 upload_max_filesize 或 post_max_size | 調整 php.ini、重啟 PHP-FPM/Apache |
| 中文檔名亂碼 | 檔案系統編碼不一致 | 重新命名為 ASCII 安全檔名(如時間戳+隨機碼) |
| 上傳 .php 檔被執行 | 上傳目錄允許 PHP 執行 | 在上傳目錄建立 .htaccess:php_flag engine off 或 SetHandler default-handler |
單檔上傳流程:表單 enctype=multipart/form-data → $_FILES 取得暫存檔 → 驗證錯誤碼/大小/MIME/副檔名 → move_uploaded_file() 移動 → 回傳結果。掌握此流程並落實安全檢查,即可避免大多數上傳漏洞。