封裝可復用的 ImageUploader 類,涵蓋 MIME 驗證、大小限制、安全重命名、移動存儲、資料庫記錄,附完整調用示例。
<?php
declare(strict_types=1);
class ImageUploader
{
private string $saveDir;
private array $allowedMimes;
private int $maxSize;
public function __construct(
string $saveDir = 'uploads/',
array $allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
int $maxSize = 2 * 1024 * 1024 // 2MB
) {
$this->saveDir = rtrim($saveDir, '/') . '/';
$this->allowedMimes = $allowedMimes;
$this->maxSize = $maxSize;
if (!is_dir($this->saveDir)) {
mkdir($this->saveDir, 0755, true);
}
}
/** 執行上傳,成功返回文件名,失敗拋出異常 */
public function upload(array $file): string
{
$this->validate($file);
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = sprintf('%s_%s.%s', date('YmdHis'), bin2hex(random_bytes(8)), $ext);
$destPath = $this->saveDir . $filename;
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
throw new RuntimeException('文件移動失敗,請檢查目錄權限');
}
// 可選:生成縮略圖、水印、壓縮等後處理
return $filename;
}
private function validate(array $file): void
{
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException($this->errorMessage($file['error']));
}
if (!in_array($file['type'], $this->allowedMimes, true)) {
throw new RuntimeException('不支援的文件類型:' . $file['type']);
}
if ($file['size'] > $this->maxSize) {
throw new RuntimeException('文件過大,限制 ' . ($this->maxSize / 1024 / 1024) . 'MB');
}
// 進階:檢測文件真實 MIME(防偽造)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$realMime = $finfo->file($file['tmp_name']);
if (!in_array($realMime, $this->allowedMimes, true)) {
throw new RuntimeException('文件內容類型不匹配:' . $realMime);
}
}
private function errorMessage(int $code): string
{
return match ($code) {
UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => '文件超過大小限制',
UPLOAD_ERR_PARTIAL => '文件上傳不完整',
UPLOAD_ERR_NO_FILE => '未選擇文件',
UPLOAD_ERR_NO_TMP_DIR => '缺少臨時目錄',
UPLOAD_ERR_CANT_WRITE => '寫入磁盤失敗',
UPLOAD_ERR_EXTENSION => '被 PHP 擴展阻止',
default => '未知上傳錯誤',
};
}
}
<?php
require_once 'ImageUploader.php';
$uploader = new ImageUploader('uploads/images');
try {
$filename = $uploader->upload($_FILES['avatar'] ?? []);
// 入庫示例(使用 PDO)
$pdo = new PDO('mysql:host=127.0.0.1;dbname=app;charset=utf8mb4', 'user', 'pass');
$stmt = $pdo->prepare('INSERT INTO avatars (user_id, filename) VALUES (?, ?)');
$stmt->execute([$_SESSION['user_id'], $filename]);
echo json_encode(['code' => 0, 'msg' => '上傳成功', 'url' => '/uploads/images/' . $filename]);
} catch (RuntimeException $e) {
http_response_code(400);
echo json_encode(['code' => 1, 'msg' => $e->getMessage()]);
}
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" accept="image/*" required>
<button type="submit">上傳頭像</button>
</form>
location ~ \.php$ { deny all; })。$_FILES['type'] + finfo 真實內容檢測。php.ini upload_max_filesize + post_max_size + 類層級雙重保障。