簡體   English   中英

PHP 會話未按預期工作

[英]PHP sessions not working as expected

所以我正在創建一個應用程序(新的 -ish 到會話)並且一直在嘗試使用會話創建一個簡單的錯誤處理語句。

為了簡化事情,讓我描述一下基礎知識。

  • 用戶在第 1 頁輸入查詢
  • 用戶按下提交
  • 加載第 2 頁以檢查查詢的值
  • 如果查詢已設置,則運行並在第 3 頁顯示結果
  • 但是,如果它是空的,則會捕獲錯誤,設置並將用戶重定向回第 1 頁

我關心的是最后一步,因為由於某種原因我無法讓它工作。

這是與錯誤有關的代碼:

第1頁相關代碼:

<?php
session_start();

$ERROR = $_SESSION['error'];

if($ERROR) {
    echo $ERROR;
}

?>

在第 2 頁:

<?

session_start();

---------------- And as we go down the file a bit ----------------

if(trim($getQuery == "")){
    $ERROR = "no search criteria entered";

    $_SESSION['error'] = $ERROR;

    if(!isset($_SESSION['error'])) {
        die("the session error was not set for some reason");
    }

    $url = "localhost:8000/mysite"; //index.php is page 1 in this case so I just redirect to the parent directory as index is loaded by default obviously in that case

    header("Location:" . $url);
}
?>

$getQuery 是在第 1 頁的查詢框中捕獲的值,並通過 post 方法發送到第 2 頁,正如您可能很自然地假設的那樣。

但是當我在查詢框中輸入任何內容然后發送查詢時,頁面刷新(當第 2 頁意識到查詢為空並且標題位置重新加載頁面時應該如此)但沒有顯示錯誤,它應該考慮我檢查在第 2 頁,它已設置。

有任何想法嗎?

干杯,--SD

您在if(trim($getQuery == "")) { ... }有一個錯字,應該是if(trim($getQuery) == "") { ... } ,因為您只想修剪$getQuery變量,而不是整個條件。 如果你改變這個,那么它會起作用。

這是一個最小的工作示例

<?php // 1.php
session_start();
$ERROR = $_SESSION['error'];
if($ERROR) {
    echo $ERROR;
}
?>

<?php // 2.php
$getQuery = ""; // This is empty so it will redirect to 1 and show error message
session_start();
if(trim($getQuery) == ""){
    $ERROR = "no search criteria entered";

    $_SESSION['error'] = $ERROR;

    if(!isset($_SESSION['error'])) {
        die("the session error was not set for some reason");
    }
    $url = "1.php"; //index.php is page 1 in this case so I just redirect to the parent directory as index is loaded by default obviously in that case
    header("Location:" . $url);
}
?>

有時瀏覽器重定向(您的標題(“位置”))可能比服務器更快。

就在重定向之前,您應該放置

session_write_close()

只是為了確保會話是為下次編寫的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM