整理 PHP 開發中高頻遇到的三大問題:Session 無法啟動、檔案上傳失敗、headers already sent 錯誤,並給出標準解決方案。
; php.ini
session.save_path = "d:/developer/php/temp" ; 必須可寫入
; 或 Linux: /tmp
錯誤:Cannot send session cookie - headers already sent
原因:session_start() 之前有輸出(空白行、HTML、BOM)。
解決:將 session_start() 放在檔案最頂端,任何輸出之前。
; 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 "上傳失敗";
}
}
?>
enctype="multipart/form-data"。$_FILES 陣列而非舊版 $HTTP_POST_FILES。chmod 777 或設定擁有者為 www-data)。