2016-12-27 60 views
-1

我認爲這可以簡單地通過權限來完成,但我似乎無法使其工作。我試圖讓頁面使用下面的代碼檢查用戶的權限,否則它會重定向到主頁。它總是重定向,但我不知道爲什麼。在php中創建管理員專用頁面

<?php 

if(!isset($_SESSION)) 
    { 
     session_start(); 
    } 

if ($_SESSION['permission'] == 0) { 
header("Location: ./index.php"); 
exit; 
} else { 
if (!isset($_SESSION['authemail'])) { 
    header("Location: ./index.php"); 
    exit;//Redirect to the index 
    } 

編輯:我添加了會話轉儲,並且userID和權限都爲空。我從這裏錯過了什麼,因爲我無法弄清楚?

<?php 
session_start(); 
include ('../config/config.php'); 

/* basic field validation */ 
$email = trim($_POST["email"]); 
$password = trim ($_POST["password"]); 

/* check if details are empty, redirect if they are */ 
if (empty($email) or empty($password)) { 
    $_SESSION["message"] = "You must enter your email and password"; 
    //Redirect to index 
    header("Location: ../index.php"); 
    exit; 
} 
/* sanitise the input */ 
$email = strip_tags($email); 
$password = strip_tags($password); 

/* SQL user selection query, with error handling for the SQL */ 
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'"; 
$result = mysqli_query($mysqli,$query) or exit("Error in query: $query. " . mysqli_error()); 

/* on query success, set sessions for email and userid */ 
if ($row = mysqli_fetch_assoc($result)) { 
    $_SESSION["authemail"] = $email; 
    $_SESSION["userid"] = $id; 
    $_SESSION["permission"] = $permission; 
    /* redirect the user to the secured page */ 
    header("Location: ../loggedin.php"); 
    } else { 
    /* display error if login was not successful and redirect to index */ 
    $_SESSION["message"] = "Could not log in as $email - $query"; 
    header("index.php"); 
    } 
    ?> 
+1

把'session_start();'放在頂部。檢查是否設置了「$ _SESSION」,這是完全多餘的。之後,'var_dump($ _ SESSION)'確保你確實擁有你期望的值。 –

+0

我們也無法判斷這些會話數組是否包含值,以及會話是否已啓動(其他地方)。錯誤報告將幫助您在這裏。無論如何你都應該開始會話。你現在擁有的是失敗的。如果會話數組有值,那麼你沒有開始會話。這就是你的代碼失敗的原因。我會把這個評論發佈爲TBH的回答,但是選擇不發表這個評論。這本身就是一個答案。 –

+0

您也可能在開頭的php標記之前在頭部之前輸出這些前導空格。 –

回答

1

嘗試在數據庫中爲某個管理員設置標誌。然後在只有管理員可以訪問的任何特定頁面上,您應該檢查此用戶變量。

if(!$user->isAdmin()){ 
    header("Location: ./login.php"); 
    exit; 
} 

如果您沒有可用的$ user對象,只需調用一個可以在數據庫中查詢必要變量的函數即可。

if(!isUserAdmin()){ 
    header("Location: ./login.php"); 
    exit; 
} 

此外,由於你的這兩種情況下重定向到index.php,你可以結合聲明:

if($_SESSION['permission'] == 0 || !isset($_SESSION['authemail'])){ 
    header("Location: ./index.php"); 
    exit; 
} 

確保您正在調試,以確保會議的值設置/獲取預期。您的代碼正在重定向,因爲其中一個條件爲真。調試並找到該錯誤。