登入成功後 header("Location: b.php") 跳轉,目標頁面無法讀取來源頁面的變數(如 $userEname)。
header("Location: ...") 發送 302 重導向,瀏覽器發起全新 HTTP 請求,原請求的變數、物件全部銷毀。而 include 在同一請求內引入檔案,變數作用域保留。
<?php // a.php
$userEname = "crystal";
$userCname = "程程";
header("Location: b.php"); // 瀏覽器重新請求 b.php
?>
// b.php
echo $userEname; // NULL!
<?php // a.php
$userEname = "crystal";
$userCname = "程程";
// ... 業務邏輯
include "b.php"; // 同一請求,變數可用
exit; // 避免繼續執行
?>
// b.php
echo $userEname; // "crystal" ✓
| 需求 | 方案 | 說明 |
|---|---|---|
| URL 實際改變、瀏覽器地址列更新、可書籤、SEO | header Location | 真正的 HTTP 重導向 |
| 內部流程控制、保留變數、避免額外請求 | include / require | 同一請求內檔案包含 |
| 表單提交後重導向防重複提交(PRG 模式) | header Location | Post-Redirect-Get 模式 |
將變數存入 Session 或暫存資料庫,header 跳轉後在目標頁讀取並清除。
session_start();
$_SESSION['flash_user'] = $userData;
header("Location: dashboard.php");
exit;
// dashboard.php
session_start();
$userData = $_SESSION['flash_user'] ?? null;
unset($_SESSION['flash_user']);