[英]PHP sessions not working as expected
所以我正在創建一個應用程序(新的 -ish 到會話)並且一直在嘗試使用會話創建一個簡單的錯誤處理語句。
為了簡化事情,讓我描述一下基礎知識。
我關心的是最后一步,因為由於某種原因我無法讓它工作。
這是與錯誤有關的代碼:
第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.