常見需求:用戶上傳新圖片覆蓋固定路徑的舊圖(如站點 Logo、用戶頭像)。本文提供前端表單與後端處理完整代碼,含類型校驗、大小限制、臨時文件移動、舊文件刪除、預覽回顯。
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>圖片替換</title></head>
<body>
<form method="post" action="changefile.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<label>選擇圖片:<input type="file" name="file" accept="image/*"></label>
<button type="submit" name="submit">上傳替換</button>
</form>
</body></html>
<?php
header('Content-Type: text/html; charset=utf-8');
function changeFile($targetPath) {
$allowed = ['jpg', 'jpeg', 'gif', 'bmp', 'png'];
$filename = $_FILES['file']['name'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
echo '<center>僅允許上傳:' . implode(', ', $allowed) . '</center>';
return;
}
// 刪除舊文件
if (file_exists($targetPath)) unlink($targetPath);
// 移動上傳文件
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)) {
echo "<center>上傳成功!預覽:<br><img src='$targetPath'></center>";
} else {
echo '<center>移動文件失敗,請檢查目錄權限</center>';
}
} else {
echo '<center>非法上傳或文件超過 2MB</center>';
}
}
// 目標文件固定路徑
changeFile(__DIR__ . '/files/1.png');
?>
$_FILES 為空。move_uploaded_file 移至目標位置。$_FILES 數據的安全檢查。getimagesize() 二次驗證 MIME 類型,防偽裝腳本。md5(time().rand()).'.'.$ext 避免衝突,資料庫記錄映射關係。php_flag engine off 或 Nginx location ~ \.php$ { deny all; } 禁用腳本執行。intervention/image)統一尺寸與質量。此最小化實現適合快速原型,企業級項目建議使用成熟上傳組件(如 Laravel MediaLibrary、Uploader)。