使用" $ _ SESSION [' authuser'] = 1"的目的是什么?在php中,为什么我们在本节中使用1

时间:2016-12-14 20:00:34

标签: php session

实际上,我无法理解为什么我们使用" $ _ SESSION [' authuser'] = 1;"在PHP代码中,我的代码如下

<?php
session_start();
$_SESSION['username'] = $_POST['user'];
$_SESSION['userpass'] = $_POST['pass'];
$_SESSION['authuser'] = 1;
//Check username and password information

if(($_SESSION['username'] == 'joe') and
($_SESSION['userpass'] == '123')) {
$_SESSION['authuser'] = 1;
} 
else 
{
echo 'Sorry, but you don\'t have permission to view this page!';
exit();
}

?>

2 个答案:

答案 0 :(得分:0)

因为会话(和cookie)支持需要它,原因有很多。

即,当您点击页面的任何链接时,您(以及访问者)每次都需要输入用户名和密码。

    <?php
    session_start();
    $_SESSION['username'] = $_POST['user'];
    $_SESSION['userpass'] = $_POST['pass'];
    $_SESSION['authuser'] = 0; // user is not authenticated (just a GUEST), default is 0...


// if visitor is priviledged, show him in, let him see the page

    if(($_SESSION['username'] == 'joe') and
    ($_SESSION['userpass'] == '123')) {
    $_SESSION['authuser'] = 1;  // insert 1 into DB and set cookie as 1 for user not to enter username and pswd anymore during browsing
    } 
    else 
    {
//else, keep guest away from a page
    echo 'Sorry, but you don\'t have permission to view this page!';
    exit(); // shut down 
    }

    ?>

答案 1 :(得分:0)

在您的情况下,使用SESSION进行用户名和userpass似乎是多余的。这可能是可能的。

<?php
session_start();
/*Do not set sessions for username and userpass, only use them in the POST array
 *Initialize authuser to 0 because by default a user is not logged in
 */
$_SESSION['authuser'] = 0;
//Check username and password information
if(($_POST['user'] == 'joe') and
  ($_POST['pass'] == '123')) { //Check the user and set it as authenticated
    $_SESSION['authuser'] = 1;
} else { //If the user is not valid, stop execution
    echo 'Sorry, but you don\'t have permission to view this page!';
    exit();
}
?>

我在这里做的是:

  • 开始会话
  • 将用户初始化为未经过身份验证(这是可选的)
  • 检查用户名和密码
    • 如果它们有效,请将用户设置为已验证
    • 如果没有,请停止执行。

请注意,在用户通过身份验证后设置用户名和密码的会话非常有用,而不是仅记住用户已记录。