如何使用session_start();“保护”php页面?

时间:2014-03-02 12:45:05

标签: php security session redirect cookies

我正在网站中创建“成员”页面,其中“成员”可以使用已存在的预定用户名和密码访问此页面。我创建了一个读取“用户名”和“密码”变量的php文件,如果值正确,则会将用户发送到此“members.php”页面,如果不是,则将其发送到另一个页面。我的问题是:如何使“members.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");
}

?>

3 个答案:

答案 0 :(得分: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)'");
    }

    ?>

答案 1 :(得分:0)

您可以尝试将members.php页面的所有代码放在

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

你也可以有一个session的函数,它会为一个成员设置一个布尔值,比如$ member = true,具体取决于userName和password,然后你可以检查

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

答案 2 :(得分: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
}


?>