【问题标题】:what is the purpose of using of "$_SESSION['authuser'] = 1" in php, why we use 1 in this section在 php 中使用 "$_SESSION['authuser'] = 1" 的目的是什么,为什么我们在本节中使用 1
【发布时间】:2017-04-30 06:58:12
【问题描述】:

实际上,我不明白我们为什么要使用 "$_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();
}

?>

【问题讨论】:

    标签: php session


    【解决方案1】:

    由于很多原因,会话(和 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 
        }
    
        ?>
    

    【讨论】:

      【解决方案2】:

      在您的情况下,对用户名和用户密码使用 SESSION 似乎是多余的。这是可能的。

      <?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();
      }
      ?>
      

      我在这里做的是:

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

      请注意,一旦用户通过身份验证,为用户名和密码设置会话可能很有用,而不是只记住用户已登录。

      【讨论】:

        猜你喜欢
        • 2021-09-18
        • 2011-07-23
        • 2014-08-24
        • 1970-01-01
        • 2020-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-01
        相关资源
        最近更新 更多