萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 檔案/圖片上傳完整教學:驗證、隨機命名、預覽、安全防護、PSR-7 現代寫法

上傳流程核心步驟

  1. 表單 enctype="multipart/form-data"
  2. PHP 檢查 $_FILES 錯誤碼
  3. 驗證 MIME/副檔名/檔案大小
  4. 產生安全檔名(隨機+雜湊)
  5. 移動暫存檔 move_uploaded_file()
  6. 回應結果(JSON/重導向)

HTML 表單

<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="hidden" name="MAX_FILE_SIZE" value="2097152"> <!-- 2MB,僅客戶端提示 -->
  <input type="file" name="avatar" accept="image/*" required>
  <button type="submit">上傳</button>
</form>

PHP 處理邏輯(完整版)

<?php
declare(strict_types=1);

const UPLOAD_DIR = __DIR__ . '/uploads/';
const ALLOWED_MIME = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const MAX_SIZE = 2 * 1024 * 1024; // 2MB

// 確保目錄存在
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0755, true);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

$file = $_FILES['avatar'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
    $errors = [
        UPLOAD_ERR_INI_SIZE => '超過 php.ini upload_max_filesize',
        UPLOAD_ERR_FORM_SIZE => '超過表單 MAX_FILE_SIZE',
        UPLOAD_ERR_PARTIAL => '上傳不完整',
        UPLOAD_ERR_NO_FILE => '未選擇檔案',
    ];
    exit('上傳錯誤:' . ($errors[$file['error']] ?? '未知錯誤'));
}

// 驗證檔案大小
if ($file['size'] > MAX_SIZE) {
    exit('檔案過大,限制 2MB');
}

// 驗證 MIME(需 finfo 擴展)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
if (!in_array($mime, ALLOWED_MIME, true)) {
    exit('不允許的檔案類型');
}

// 產生安全檔名
$ext = match ($mime) {
    'image/jpeg' => 'jpg',
    'image/png'  => 'png',
    'image/gif'  => 'gif',
    'image/webp' => 'webp',
    default      => 'bin',
};
$filename = bin2hex(random_bytes(16)) . '.' . $ext;
$dest = UPLOAD_DIR . $filename;

// 移動檔案
if (!move_uploaded_file($file['tmp_name'], $dest)) {
    exit('檔案儲存失敗');
}

// 成功回應
header('Content-Type: application/json');
echo json_encode([
    'success' => true,
    'filename' => $filename,
    'url' => '/uploads/' . $filename,
    'size' => $file['size'],
], JSON_UNESCAPED_UNICODE);

前端預覽與 AJAX 上傳

<input type="file" id="avatar" accept="image/*">
<img id="preview" style="max-width:200px;display:none">
<script>
document.getElementById('avatar').addEventListener('change', e => {
    const file = e.target.files[0];
    if (file) {
        document.getElementById('preview').src = URL.createObjectURL(file);
        document.getElementById('preview').style.display = 'block';
    }
});

// AJAX 上傳
async function upload() {
    const formData = new FormData();
    formData.append('avatar', document.getElementById('avatar').files[0]);
    const res = await fetch('upload.php', {method: 'POST', body: formData});
    const data = await res.json();
    console.log(data);
}
</script>

安全防護清單

  • ✅ 驗證 MIME(finode)而非只看副檔名
  • ✅ 限制檔案大小(php.ini + 程式碼雙重)
  • ✅ 隨機檔名 + 白名單副檔名
  • ✅ 上傳目錄**禁止執行腳本**(Nginx/Apache 設定)
  • ✅ 掃描惡意代碼(ClamAV、VirusTotal API)
  • ✅ 圖片重新處理(GD/Imagick 裁切、壓縮、去除 EXIF)
  • ✅ 儲存於 Web 根目錄外,或透過 PHP 讀取輸出

現代框架整合(PSR-7 / Symfony HttpFoundation)

use Psr\Http\Message\UploadedFileInterface;

function handleUpload(UploadedFileInterface $file): string {
    $file->moveTo(UPLOAD_DIR . $filename);
    return $filename;
}

原始來源:www.111cn.net

copyright © 萬盛學電腦網 all rights reserved