2014-03-02 102 views
0

我在一個網站內製作一個「會員」頁面,其中「會員」可以使用預先確定的用戶名和密碼訪問此頁面。我做了一個讀取「username」和「passwrod」變量的php文件,如果這些值是正確的,用戶將被髮送到這個「members.php」頁面,如果沒有,它會被髮送到另一個頁面。我的問題是:我如何才能讓「members.php」頁面只提供給已經提交了正確用戶名和密碼的用戶,如果用戶不在「會話」中被重定向到訪問表單的頁面。如何使用session_start();「保護」php頁面?

<?php 

session_start(); 

$username = $_POST['username']; 
$password = $_POST['password']; 

if ($username == 'correctusername' AND $password == 'correctpassword') 
{ 

    header("location:members.php"); 

} 
else { 

    header("location:wrong.php"); 
} 

?> 

回答

0
 <?php 

    $username = $_POST['username']; 
    $password = $_POST['password']; 

    if ($username == 'correctusername' AND $password == 'correctpassword') 
    { 
    //apart from session you can use this urlencode() and get on members page with urldecode 
     header("location:members.php?foo='urlencode($username)'"); 

    } 
    else { 

     header("location:wrong.php?foo='urlencode($username)'"); 
    } 

    ?> 
0

你可以嘗試把所有的代碼爲members.php頁面內

if (isset($_SESSION)){ 
    //all code for the page goes here 
}else{ 
// redirect to other page 
} 

您還可以對會話的功能將設置一個布爾值,說$成員=對於會員而言取決於用戶名和密碼,那麼你可以檢查

if(isset($_SESSION) && $_SESSION['member']{ 
    //all code for the page for view by members only goes here 
}else{ 
    redirect to another page 
} 
0

有點像?:

<?php 

session_start(); 

if(isset($_SESSION['loggedIn']) && ($_SESSION['loggedIn']=='true')){ 
//the session variable is already set for this user so not needed to check again 
header("location:members.php"); 
exit; 
} 
else if(isset($_POST['username']) && isset($_POST['password'])){ 
//if the user is submitting for the first time, check. 
$username = $_POST['username']; 
$password = $_POST['password']; 

    if ($username == 'correctusername' AND $password == 'correctpassword') 
    { 
    //setting session so on next visit to this page, they are 
    //automatically redirected 
    $_SESSION['loggedIn'] = 'true'; 
    header("location:members.php"); 
    exit; 

    } 
    else { 
    //if posted values are wrong 
    header("location:wrong.php"); 
    exit; 
    } 
} 
else { 
//this block evaluates to true if session has not been set and if no 
//'username' or 'password' has been posted 
} 


?>