萬盛學電腦網

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

PHP header() 跳轉導致變數丟失?改用 include 解決參數傳遞問題

問題場景

登入成功後 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!

正確做法:include 內部跳轉

<?php // a.php
$userEname = "crystal";
$userCname = "程程";
// ... 業務邏輯
include "b.php"; // 同一請求,變數可用
exit; // 避免繼續執行
?>

// b.php
echo $userEname; // "crystal" ✓

何時用 header、何時用 include?

需求方案說明
URL 實際改變、瀏覽器地址列更新、可書籤、SEOheader Location真正的 HTTP 重導向
內部流程控制、保留變數、避免額外請求include / require同一請求內檔案包含
表單提交後重導向防重複提交(PRG 模式)header LocationPost-Redirect-Get 模式

進階:需同時保留變數又要改變 URL

將變數存入 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']);
copyright © 萬盛學電腦網 all rights reserved