萬盛學電腦網

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

PHP 檔案上傳完整實作:驗證、安全、重命名、日誌、列表管理

PHP 檔案上傳完整實作:驗證、安全、重命名、日誌、列表管理

檔案上傳是 Web 開發高風險功能,必須嚴格驗證類型、大小、內容、路徑,並記錄審計日誌。本文提供一個功能完整、安全導向的單檔案上傳管理器,涵蓋前端表單、後端處理、檔案列表、刪除功能。

核心安全檢查清單

  1. MIME 型別白名單:`$_FILES['file']['type']` (瀏覽器提供,不可信) + `finfo_file()` (實際偵測)。
  2. 副檔名白名單:雙重保險。
  3. 檔案大小限制:PHP `upload_max_filesize`、`post_max_size`、腳本層雙重限制。
  4. 檔名安全化:移除路徑字元、特殊字元、統一用亂數/雜湊命名。
  5. 儲存路徑隔離:上傳目錄設為不可執行 (Nginx/Apache `location ~ \.php$ { deny all; }`)、存放於 Webroot 外最佳。
  6. 權限最小化:目錄 0755、檔案 0644、不給執行權限。
  7. 審計日誌:記錄 IP、時間、原始檔名、儲存檔名、MIME、大小、結果。

完整單檔上傳管理器 (upload_manager.php)

<?php
declare(strict_types=1);

const UPLOAD_DIR = __DIR__ . '/uploads';
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
const ALLOWED_MIMES = ['image/jpeg','image/png','image/gif','image/webp','application/pdf'];
const ALLOWED_EXTS = ['.jpg','.jpeg','.png','.gif','.webp','.pdf'];
const LOG_FILE = __DIR__ . '/upload.log';

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

// 初始化變數
$message = '';
$files = [];

// --- 處理刪除 ---
if (isset($_GET['delete']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $target = resolvePath($_GET['delete']);
    if ($target && is_file($target) && unlink($target)) {
        logAction('DELETE', $_SERVER['REMOTE_ADDR'], basename($target));
        $message = '刪除成功';
    } else {
        $message = '刪除失敗或檔案不存在';
    }
}

// --- 處理上傳 ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $f = $_FILES['file'];
    $ip = $_SERVER['REMOTE_ADDR'];

    // 1. 錯誤碼檢查
    if ($f['error'] !== UPLOAD_ERR_OK) {
        $message = '上傳錯誤代碼: ' . $f['error'];
        logAction('UPLOAD_FAIL', $ip, $f['name'], $f['type'], $f['size'], $message);
    }
    // 2. 大小檢查
    elseif ($f['size'] > MAX_SIZE) {
        $message = '檔案超過 ' . (MAX_SIZE/1024/1024) . 'MB 限制';
        logAction('UPLOAD_FAIL', $ip, $f['name'], $f['type'], $f['size'], $message);
    }
    // 3. MIME 偵測 (finfo)
    else {
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $realMime = $finfo->file($f['tmp_name']);
        $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
        $ext = '.' . $ext;

        // 4. 雙重驗證
        if (!in_array($realMime, ALLOWED_MIMES, true) || !in_array($ext, ALLOWED_EXTS, true)) {
            $message = "檔案類型不允許 (MIME: $realMime, 副檔名: $ext)";
            logAction('UPLOAD_FAIL', $ip, $f['name'], $realMime, $f['size'], $message);
        } else {
            // 5. 安全檔名:隨機 + 原副檔名
            $newName = bin2hex(random_bytes(12)) . $ext;
            $dest = UPLOAD_DIR . DIRECTORY_SEPARATOR . $newName;

            if (move_uploaded_file($f['tmp_name'], $dest)) {
                @chmod($dest, 0644);
                $message = '上傳成功:' . $newName;
                logAction('UPLOAD_OK', $ip, $f['name'], $realMime, $f['size'], $newName);
            } else {
                $message = '伺服器儲存失敗';
                logAction('UPLOAD_FAIL', $ip, $f['name'], $realMime, $f['size'], $message);
            }
        }
    }
}

// --- 列出檔案 ---
$dh = opendir(UPLOAD_DIR);
while (($fn = readdir($dh)) !== false) {
    if ($fn === '.' || $fn === '..' || is_dir($fn)) continue;
    $fp = UPLOAD_DIR . DIRECTORY_SEPARATOR . $fn;
    $stat = stat($fp);
    $files[] = [
        'name' => $fn,
        'size' => $stat['size'],
        'mtime' => $stat['mtime'],
        'mime' => mime_content_type($fp) ?: 'unknown',
        'url' => 'uploads/' . rawurlencode($fn),
        'delete_url' => '?delete=' . rawurlencode($fn),
    ];
}
closedir($dh);

// 排序:新到舊
usort($files, fn($a,$b) => $b['mtime'] <=> $a['mtime']);

// --- 工具函數 ---
function resolvePath(string $name): string|false {
    $target = realpath(UPLOAD_DIR . DIRECTORY_SEPARATOR . $name);
    $root = realpath(UPLOAD_DIR);
    return ($target && str_starts_with($target, $root)) ? $target : false;
}

function logAction(string $action, string $ip, string $origName, string $mime, int $size, string $detail): void {
    $line = sprintf("[%s] %s | IP=%s | ORIG=%s | MIME=%s | SIZE=%d | %s\n",
        date('Y-m-d H:i:s'), $action, $ip, $origName, $mime, $size, $detail);
    @file_put_contents(LOG_FILE, $line, FILE_APPEND | LOCK_EX);
}
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>檔案上傳管理器</title>
<style>
body{font-family:sans-serif;max-width:800px;margin:2rem auto;padding:0 1rem}
table{width:100%;border-collapse:collapse;margin-top:1rem}
th,td{border:1px solid #ddd;padding:.5rem;text-align:left}
th{background:#f5f5f5}
.msg{padding:.75rem;border-radius:4px;margin:1rem 0}
.ok{background:#d4edda;color:#155724;border:1px solid #c3e6cb}
.err{background:#f8d7da;color:#721c24;border:1px solid #f5c6cb}
form{margin:1rem 0;padding:1rem;border:1px solid #eee;border-radius:4px}
button,input[type=submit]{padding:.5rem 1rem;background:#007bff;color:#fff;border:none;border-radius:3px;cursor:pointer}
button.danger{background:#dc3545}
</style></head><body>
<h1>檔案上傳管理器</h1>
<?php if ($message): ?><div class="msg <?= str_starts_with($message,'上傳成功')||str_starts_with($message,'刪除成功')?'ok':'err' ?>"><?= htmlspecialchars($message) ?></div><?php endif; ?>

<form enctype="multipart/form-data" method="post">
  <input type="file" name="file" required>
  <input type="submit" value="上傳">
  <small>允許: <?= implode(', ', ALLOWED_EXTS) ?> | 最大 <?= MAX_SIZE/1024/1024 ?>MB</small>
</form>

<table>
  <thead><tr><th>檔名</th><th>大小</th><th>類型</th><th>上傳時間</th><th>操作</th></tr></thead>
  <tbody>
  <?php foreach ($files as $f): ?>
    <tr>
      <td><a href="<?= $f['url'] ?>" target="_blank"><?= htmlspecialchars($f['name']) ?></a></td>
      <td><?= $f['size'] < 1024 ? $f['size'].'B' : ($f['size'] < 1048576 ? round($f['size']/1024,1).'KB' : round($f['size']/1048576,1).'MB') ?></td>
      <td><?= htmlspecialchars($f['mime']) ?></td>
      <td><?= date('Y-m-d H:i:s', $f['mtime']) ?></td>
      <td>
        <form method="post" action="<?= $f['delete_url'] ?>" onsubmit="return confirm('確定刪除?')">
          <button type="submit" class="danger">刪除</button>
        </form>
      </td>
    </tr>
  <?php endforeach; ?>
  <?php if (!$files): ?><tr><td colspan="5" style="text-align:center;color:#999">暫無檔案</td></tr><?php endif; ?>
  </tbody>
</table>
</body></html>

Nginx/Apache 安全配置 (上傳目錄禁用執行)

# Nginx
location /uploads/ {
    location ~ \.php$ { return 403; } # 禁止執行 PHP
    add_header X-Content-Type-Options nosniff;
}

# Apache (.htaccess in /uploads)

    Require all denied

Options -ExecCGI
AddHandler cgi-script .php .php3 .php4 .php5 .phtml .pl .py .jsp .asp .sh .cgi

大檔案/分塊上傳進階方案

  • 前端:uppy.js、dropzone.js、WebUploader (分片、斷點續傳、進度條)
  • 後端:合併分片、驗證完整性 (MD5/SHA256)、異步處理 (佇列)
  • 雲端直傳:預簽名 URL (AWS S3、GCS、阿里云 OSS) 繞過應用伺服器,減輕頻寬壓力。
copyright © 萬盛學電腦網 all rights reserved