一千萬個為什麽

搜索

無法在無cookie的PHP會話上訪問會話變量

我試圖使用PHP會話而不使用cookie。我在php.ini文件中啟用了session.use_trans_sid並禁用了session.use_cookies。我還在我的firefox瀏覽器中禁用了cookie。現在,當我在頁面之間導航時,我無法訪問上一頁中的會話對象集中的變量。順便說一句,我知道使用會話ID作為URL的一部分不是推薦的方法。

我在下面提供了兩個頁面的示例代碼片段 - page1.php和page2.php。 Page1.php將會話對象中的變量設置為true,page2.php檢查此變量的值並相應地執行操作。

page1.php中</強>

<?php
session_start();
if (isset($_REQUEST["user"]))
{
    $_SESSION["name"] = true;
    $host = $_SERVER["HTTP_HOST"];
    $path = dirname($_SERVER["PHP_SELF"]);
    header("Location: http://$host$path/page2.php");
    exit;
}
?>


<head>
<title>Page1</title>
</head>
<body>
<form method="get" action="/page1.php">
Name:<input type="text" name="user"/>
<input type="submit" value="Login"/>
</form> </body> </html>

使page2.php </強>

<?php
session_start();
if ($_SESSION["name"])
{
    echo("

Name set.

");
}
else
{
     echo("

Name NOT set.

");
} 
?>

最佳答案

I have resolved the issue. Looks like PHP will not pass the session ID during re-directs as part of the re-direction URL even if the re-direct is to a page within the same website. This is why the session variable was not available within page2.php above and the output was always "Name NOT set". So I changed my re-direct URL on page1.php to have the session ID as part of it & that did the trick.

$sid = session_name() . "=" . session_id();
header("Location: http://$host$path/page2.php?$sid");

轉載註明原文: 無法在無cookie的PHP會話上訪問會話變量