每個 PHP 新手都會踩的坑,其實都有標準解法。本文整理 14 大高頻問題,附原因分析、修正代碼與預防措施,助你少走彎路。
現象:$var 取不到值
原因:PHP 4.2+ register_globals=Off 預設關閉
解法:使用超全域陣列 $_GET['var'], $_POST['var'], $_SESSION['var']
現象:test.php?a=中文 導致 Internal Server Error
解法:URL 編碼傳遞 urlencode('中文'),接收端 urldecode()
現象:Session 資料不持久化
原因:php.ini session.save_path = /tmp (Linux 路徑)
解法:改為 Windows 有效路徑 session.save_path = "C:/Windows/Temp"
建議:display_errors=On, error_reporting=E_ALL
生產:display_errors=Off, log_errors=On, error_log=/var/log/php_errors.log
變數未定義預防:isset($var) ? $var : '' 或 $_POST['x'] ?? '' (PHP 7+)
原因:Windows 無 sendmail,需 SMTP 伺服器
方案:使用 PHPMailer/Symfony Mailer 等庫,透過 SMTP (Gmail、SendGrid、自建) 發送
mysql -u root
UPDATE mysql.user SET authentication_string=PASSWORD('newpass') WHERE User='root';
FLUSH PRIVILEGES;
?>
MySQL 8.0+ 使用 ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpass';
三大原因:
header()/session_start()/setcookie() 前有輸出 (echo、空白、BOM)include 的檔案結尾有關閉標籤 ?> 後的空白/換行最佳實踐:純 PHP 檔案省略結束標籤 ?>
必須重啟 Web Server:Apache systemctl restart httpd, Nginx+PHP-FPM systemctl restart php-fpm
驗證:phpinfo() 查看 Loaded Configuration File
歷史內容,現代環境請用 IIS 10+ + PHP 8 + FastCGI 模組
黃金法則:echo $sql; die; 輸出實際 SQL,檢查變數插值、引號、保留字
進階:啟用 MySQL 慢查詢日誌、一般查詢日誌
使用 __DIR__ 基準:require __DIR__ . '/../config.php';
錯誤:foreach ($users as $u) { $posts = query("SELECT * FROM posts WHERE user_id=$u->id"); }
正確:單次 JOIN 或 WHERE user_id IN (...) 批次查詢
嚴禁:INSERT ... VALUES ('pwd')
標準:password_hash($pwd, PASSWORD_DEFAULT) 存儲,password_verify($input, $hash) 驗證
<?php
date_default_timezone_set('Asia/Taipei'); // 或 Asia/Shanghai
// php.ini: date.timezone = "Asia/Taipei"
?>
坑踩多了就是經驗,但聰明人學別人踩過的坑。