萬盛學電腦網

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

PHP 圖片上傳完整實現:客戶端表單與服務端處理

圖片上傳是 Web 開發基礎功能,涉及前端表單構造、後端文件驗證、重命名、存儲、安全防護等多個環節。本文提供一套完整的前後端代碼,涵蓋格式驗證、隨機命名、目錄自動創建、錯誤處理等實用技巧。

前端表單

<form name="form1" method="post" action="upload.php" enctype="multipart/form-data">
    <input type="file" name="pic" accept="image/*" required>
    <input type="submit" name="submit" value="開始上傳" class="button">
</form>

關鍵點:enctype="multipart/form-data"、accept="image/*" 限制文件選擇框過濾。

後端處理流程

  1. 配置上傳目錄:按日期創建子目錄,避免單目錄文件過多。
  2. 文件類型驗證:檢查 MIME 類型與擴展名雙重驗證。
  3. 文件大小限制:配合 php.ini 的 upload_max_filesize、post_max_size。
  4. 安全重命名:使用 md5(時間.隨機數) + 原擴展名,防止覆蓋與腳本注入。
  5. 移動文件:move_uploaded_file() 確保文件來自合法上傳。
  6. 返回結果:JSON 格式回傳狀態、路徑、錯誤信息。

核心 PHP 代碼

<?php
header('Content-Type: application/json; charset=utf-8');

$config = [
    'rootPath'    => __DIR__ . '/uploads/',
    'maxSize'     => 5 * 1024 * 1024, // 5MB
    'allowTypes'  => ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
    'allowExts'   => ['jpg', 'jpeg', 'png', 'gif', 'webp'],
];

$resp = ['code'=>0, 'msg'=>'', 'data'=>null];

if (!isset($_FILES['pic']) || $_FILES['pic']['error'] !== UPLOAD_ERR_OK) {
    $resp['msg'] = '上傳失敗:' . ($_FILES['pic']['error'] ?? '未知錯誤');
    echo json_encode($resp);
    exit;
}

$file = $_FILES['pic'];

// 1. 大小檢查
if ($file['size'] > $config['maxSize']) {
    $resp['msg'] = '文件過大,限制 ' . ($config['maxSize']/1024/1024) . 'MB';
    echo json_encode($resp);
    exit;
}

// 2. MIME 類型檢查
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (!in_array($mime, $config['allowTypes'])) {
    $resp['msg'] = '禁止的文件類型:' . $mime;
    echo json_encode($resp);
    exit;
}

// 3. 擴展名檢查
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $config['allowExts'])) {
    $resp['msg'] = '禁止的擴展名:' . $ext;
    echo json_encode($resp);
    exit;
}

// 4. 目標目錄(按日期)
$dateDir = date('Y/m/d/');
$destDir = $config['rootPath'] . $dateDir;
if (!is_dir($destDir)) {
    mkdir($destDir, 0755, true);
}

// 5. 隨機文件名
$newName = md5(microtime(true) . mt_rand(1000,9999)) . '.' . $ext;
$destPath = $destDir . $newName;

// 6. 移動文件
if (!move_uploaded_file($file['tmp_name'], $destPath)) {
    $resp['msg'] = '文件保存失敗,請檢查目錄權限';
    echo json_encode($resp);
    exit;
}

// 7. 成功返回
$resp['code'] = 1;
$resp['msg'] = '上傳成功';
$resp['data'] = [
    'path' => $dateDir . $newName,
    'fullPath' => $destPath,
    'size' => $file['size'],
    'mime' => $mime,
];
echo json_encode($resp);

安全加固建議

  • 禁用腳本執行權限:上傳目錄配置 Nginx/Apache 禁止 PHP 腳本執行。
  • 二次驗證圖片內容:使用 getimagesize() 或 imagecreatefromstring() 驗證是否真實圖片。
  • 病毒掃描:對接 ClamAV 等殺毒引擎異步掃描。
  • 限制上傳頻率:基於 IP/用戶 ID 限制每分鐘上傳次數。
  • HTTPS 傳輸:防止中間人竄改上傳內容。

前端 AJAX 異步上傳(可選)

// 使用 FormData + fetch
const formData = new FormData();
formData.append('pic', fileInput.files[0]);
fetch('upload.php', {method:'POST', body:formData})
    .then(r => r.json())
    .then(res => { if(res.code) console.log('成功', res.data); else alert(res.msg); });

這套方案從前端到後端覆蓋了圖片上傳的完整鏈路,代碼結構清晰,安全措施完善,可直接投入生產環境或作為基礎組件進一步擴展。

copyright © 萬盛學電腦網 all rights reserved