2016-12-01 177 views
0

早上好/晚上,PHP登錄和會話

我被卡住了,我需要一些PHP幫助。

我想編碼管理儀表板。我想檢查用戶是否已登錄,如果沒有,則重定向到登錄頁面。

我的index.php是這樣的:

<?php 
$pagename ="Index"; 

@require_once('inc/head.php'); 
?> 
<body> 
CONGRATS! Welcome to the Admin dashboard. 
</body> 
</html> 

我的登錄頁面:

<?php 
$pagename = "login"; 
$adminUser = "admin"; 
$adminPass = "admin"; 

@require_once('inc/head.php'); 

// If POST is submitted and IDs match the ones set 
if($_SERVER["REQUEST_METHOD"] == "POST") 
{ 
if($_POST["username"] == $adminUser && $_POST["password"] == $adminPass) 

    { 
    session_start(); 
    $_SESSION["username"] = $adminUser; 
    $_SESSION["login"] = true; 
    echo '<script>alert("Congrats, you logged in"); 
    window.location = "index.php"; </script>'; 

/* I skip the line underneath because for unknown reasons my code 
    Doesn't fully run through. So I redirected with the JS above instead. 

    header("Location: index.php"); 
    exit(); */ 
    }else{ 
    echo '<script>alert("Incorrect username or password!'");</script>'; 
    } 
} 
?> 

<html> 
<!-- login page here --> 
</html> 

而且在這裏不用我head.php:

<?php 

    // If we AREN'T on the login page , check if session exist. If not send to login 
if($pagename != "login") 
{  if(!$_SESSION['login']) 
    { 
     header('location: login.php'); 
     exit(); 
    } 
} 
?> 

有很多的東西錯了與此,我知道,但截至目前我試圖解決我的登錄問題。每當我登錄時,我都會彈出JS說我成功登錄了,但我沒有被重定向到索引。我想我得到發送到我的index.php(沒有理由我的JS重定向到NOT功能),但我的索引發送我回到登錄,我不明白爲什麼。

+1

在會話中的所有頁面開始使用他們?似乎不是head.php文件的情況。 –

+0

'session_start();'在** head.php中缺少** –

+0

但是我只想在用戶登錄後創建一個會話。或者我需要創建一個,無論如何,當用戶登錄時爲其添加值在? – FrenchMajesty

回答

0

開始會話head.php page。

head.php

<?php 
if($pagename != "login") { 
    session_start(); 
    if(!$_SESSION['login']) { 
    header('location: login.php'); 
    exit(); 
    } 
} 
?>