萬盛學電腦網

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

PHP 最簡單檔案上傳實作:move_uploaded_file() 完整範例

核心概念

PHP 內建 move_uploaded_file() 函式可將暫存檔案移動到指定目錄,是實作檔案上傳的關鍵。上傳流程:表單 enctype="multipart/form-data" → $_FILES 取得暫存路徑 → 移動到永久儲存位置。

最小可行程式碼

<?php
$tmpName = $_FILES['myupload']['tmp_name'];
$destPath = '/path/to/dest/' . $_FILES['myupload']['name'];

if (!move_uploaded_file($tmpName, $destPath)) {
    echo 'An error has occurred moving the uploaded file.<br>';
    echo 'Please ensure that if safe_mode is on that the UID PHP is using matches the file.';
    exit;
} else {
    echo 'The file has been successfully uploaded!';
}
?>

必要的 HTML 表單

<form action="upload.php" method="POST" enctype="multipart/form-data">
  <input type="file" name="myupload">
  <input type="submit" value="上傳">
</form>

關鍵注意事項

  • 目錄權限:目的資料夾必須可寫入(Linux 下通常設為 755 或 777,視伺服器設定)。
  • 檔名衝突:建議重新命名(如加上時間戳記或亂數)避免覆蓋。
  • 安全驗證:實務上必須檢查 MIME 類型、副檔名、檔案大小,防止惡意腳本上傳。
  • php.ini 設定:file_uploads = On、upload_max_filesize、post_max_size 需符合需求。

進階建議

生產環境建議:

  1. 使用 $_FILES['myupload']['error'] 判斷上傳狀態(UPLOAD_ERR_OK 為 0)。
  2. 搭配 pathinfo() 擷取副檔名,配合白名單驗證。
  3. 將檔案儲存在 Web 根目錄外,或透過 PHP 輸出檔案內容,避免直接執行上傳的腳本。
copyright © 萬盛學電腦網 all rights reserved