2014-03-02 78 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 
} 


?>