2011-09-08 12 views
0

這裏是我的index.phpPHP會話沒有按預期行事 - 我該如何解決?

<?php 
session_start(); 
if($_SESSION['authorizedreferral'] == false){  //login.php sets 'authorizedreferral' to false, and redirects to here. That way, login.php can't be accessed directly. 
    session_destroy();        //destroy the session, so the 'authorizedreferral' session is revaluated each time. 
    echo "<h1>No ticky, no washy!</h1>";   //Sorry, don't pass go, and don't collect $200 

}elseif(!isset($_COOKIE['loggedin'])){    //if there isn't a 'loggedin' cookie set, forward to the login.php page 
    $_SESSION['authorizedreferral'] = true;   //yes, this is a correct referral. Otherwise, login.php will kick you out! 
    header("Location: login.php");     //forward to login.php 
    exit;           //need this for some reason? 
} 

?> 

這裏的login.php:

<?php 
    session_start();           //start the session 
    if(!isset($_SESSION['authorizedreferral'])){    //if 'authorizedreferral' isn't set (i.e. someone just loads login.php directly) 

     $_SESSION['authorizedreferral'] = false;    //set 'authorizedreferral' to false - they aren't allowed here! 
     header('Location: http://'.$_SERVER["HTTP_HOST"]);  //and ship 'em back home! 
     exit;             //need this for some reason 

    } 


?> 

這裏有可能出現的情況:

  1. 用戶進入的index.php - 因爲他們的避風港沒有登錄(沒有登錄cookie),他們會被髮送到login.php頁面進行登錄。
  2. 用戶試圖直接訪問login.php - 它們被髮送回index.php,並得到消息「No Ticky,no washy!」

但是,現在,用戶總是收到「沒有Ticky,沒有Washy!」當訪問index.php頁面時。我錯過了什麼?

http://webify.nitrouscloud.net

回答

4

的用戶第一次來到現場,他們將有一個空會話。你的第一個if()子句將始終爲true,因爲PHP的類型轉換規則:

if($_SESSION['authorizedreferral'] == false) 

會議是空的,所以在會議上沒有authorizedreferal價值,所以PHP返回一個「空」(和取消設置陣列鍵警告)。在PHP的類型轉換規則下,null == false爲TRUE。

你必須改變你的邏輯來檢查,如果用戶登錄(不要存儲在cookie - 它存儲在會話),並重定向到登錄頁面:

session_start(); 
if (!isset($_SESSION['loggedin']) || ($_SESSION['loggedin'] === false)) { 
    header("Location: login.php"); 
} 

的另一種方法是用嚴格的比較操作:

if ($_SESSION['authorizedreferral'] !== true) { 
    ... 
} 

如果真有那設置爲布爾值true的authorizedreferral值,因爲這隻會成功。不過,您仍然可以獲得全新用戶的未設置陣列警告。

+0

太棒了 - 不知道有關'===',還是關於默認的會話設置。很有幫助! – Jared