萬盛學電腦網

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

PHP 常見問題:Session、檔案上傳與 Header 錯誤解決

整理 PHP 開發中高頻遇到的三大問題:Session 無法啟動、檔案上傳失敗、headers already sent 錯誤,並給出標準解決方案。

1. Session 設定與常見錯誤

; php.ini
session.save_path = "d:/developer/php/temp"  ; 必須可寫入
; 或 Linux: /tmp

錯誤:Cannot send session cookie - headers already sent
原因:session_start() 之前有輸出(空白行、HTML、BOM)。
解決:將 session_start() 放在檔案最頂端,任何輸出之前。

2. 檔案上傳設定

; php.ini
upload_tmp_dir = "d:/temp"
file_uploads = On
upload_max_filesize = 2M
post_max_size = 8M
<form action="upload.php" method="post" enctype="multipart/form-data">
  <input type="hidden" name="MAX_FILE_SIZE" value="1048576">
  <input type="file" name="userfile">
  <input type="submit" name="upload" value="上傳">
</form>
<?php
if (isset($_POST['upload'])) {
    $target = $_FILES['userfile']['name'];
    if (file_exists($target)) unlink($target);
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $target)) {
        echo "上傳成功";
    } else {
        echo "上傳失敗";
    }
}
?>

3. 關鍵提醒

  • 表單必須加 enctype="multipart/form-data"。
  • 使用 $_FILES 陣列而非舊版 $HTTP_POST_FILES。
  • 上傳目錄需給寫入權限(Linux: chmod 777 或設定擁有者為 www-data)。
  • 生產環境務必驗證檔案型別(MIME、副檔名、內容掃描),防止惡意腳本上傳。
copyright © 萬盛學電腦網 all rights reserved