Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
“使用”的目的是什么$_会话[';authuser';]=1";在php中,为什么在本节中使用1_Php_Session - Fatal编程技术网

“使用”的目的是什么$_会话[';authuser';]=1";在php中,为什么在本节中使用1

“使用”的目的是什么$_会话[';authuser';]=1";在php中,为什么在本节中使用1,php,session,Php,Session,实际上,我不明白为什么我们在php代码中使用“$\u SESSION['authuser']=1;”,我的代码如下所示 <?php session_start(); $_SESSION['username'] = $_POST['user']; $_SESSION['userpass'] = $_POST['pass']; $_SESSION['authuser'] = 1; //Check username and password information if(($_SESSION[

实际上,我不明白为什么我们在php代码中使用“$\u SESSION['authuser']=1;”,我的代码如下所示

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

?>

因为会话(和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 
    }

    ?>

在您的案例中,对用户名和用户密码使用会话似乎是多余的。这是可能的

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

我在这里做的是:

  • 开始会话
  • 将用户初始化为未经身份验证(这是可选的)
  • 检查用户名和密码
    • 如果有效,请将用户设置为已验证
    • 如果没有,则停止执行
请注意,一旦用户通过身份验证,为用户名和密码设置会话可能会很有用,而不是只记住用户已登录