header('Location: ...') 只是發送 HTTP 302 標頭,**不會** 自動終止腳本執行。瀏覽器收到標頭會跳轉,但伺服器端 PHP 繼續往下跑。若後續有危險操作(刪除資料、寫入日誌、發送郵件),將造成嚴重安全漏洞。
<?php
if ($authorized) {
header('Location: https://example.com/dashboard');
}
// 這行依然會被執行!
file_put_contents('log.txt', '敏感操作已執行');
<?php
if ($authorized) {
header('Location: https://example.com/dashboard');
exit; // 或 die();
}
file_put_contents('log.txt', '這行不會執行');
function redirect(string $url, int $status = 302): never
{
header('Location: ' . $url, true, $status);
exit;
}
// 使用
redirect('/login.php');
宣告回傳型別 `never`(PHP 8.1+)可讓靜態分析工具識別流程終止。
若遇到 Class 'SoapClient' not found,請在 php.ini 中啟用:
extension=soap
extension=openssl
Windows 環境下對應 `php_soap.dll`、`php_openssl.dll`。修改後重啟 Apache/Nginx+php-fpm。
| 語法 | 說明 |
|---|---|
var_dump($var) | 輸出變數型別與值(含結構) |
$GLOBALS | 當前腳本所有全域變數 |
get_defined_vars() | 當前作用域所有已定義變數(含超全域) |
get_defined_constants() | 所有已定義常數 |