1

如何使用登录使用 2 文件设置会话?主页 > 登录 > 主页
我的代码做错了吗?谢谢。

主页.php

<?php
    session_start();
?>
<!DOCTYPE html>
<html><head><title></title></head>
<body>
<?php
    if($_SESSION['account']){
        print"login successful";
        //do something
    }
    else{
        print"login invalid";
        print"
            <form method=\"post\" action=\"login.php\">
                account: <input type=\"text\" name=\"account\"><br>
                password: <input type=\"text\" name=\"password\"><br>
                <input type=\"submit\" value=\"login\">
            </form>
        ";
    }
?>
</body>
</html>

登录.php

$account = mysql_escape_string($_POST['account']);
$password = mysql_real_escape_string($_POST['password']);
if($account == 'myaccount' && $password == 'mypassword'){
    session_start();
    $_SESSION['account'] = $account;
    $_SESSION['password'];
    print"<meta http-equiv=\"refresh\" content=\"0;url=home.php\">";
    header("location: home.php");
    exit();
}
else{
    print"<meta http-equiv=\"refresh\" content=\"0;url=home.php\">";
    header("location: home.php");
    exit();
}
4

3 回答 3

1

您没有在$_SESSION阵列上存储任何数据。

尝试:

$_SESSION['account'] = true; // Or something else that evaluates to true and is relevant.
$_SESSION['password'] = 'please, anything but your password plaintext. think of the children';

这样,当您在 home.php 上测试登录操作的结果时:

if($_SESSION['account']){
    print"login successful";
    //do something
}

你可以满足条件。

于 2013-01-16T22:47:36.400 回答
1

根据您的脚本:

$_SESSION['account'];
$_SESSION['password'];

应该是这样的:

$_SESSION['account'] = $account;
$_SESSION['password'] = $password;

但请注意,请不要在生产站点中使用它。这将无法验证用户。

您不能将会话用作登录一个人并使他们保持登录的唯一方法。会话很容易被劫持。一个好的用户认证系统将:

加密密码

在数据库中存储用户信息

收集会话信息并设置它

现在为了让用户保持登录状态,每次他们访问新页面时,您将使用 seesion id、密码、用户 ip 和会话变量来验证用户并允许他们查看页面。基本上你会创建一个函数或一个类来以安全的方式处理它。

现在对于那些刚刚开始学习 php 的人来说,已经有很多很棒的登录脚本了。任何对其用户进行身份验证的好网站,都从一个非常好的用户身份验证系统开始,然后在其中构建一个网站。

于 2013-01-16T22:49:56.740 回答
0

换行:

if($_SESSION['account']){
  print"login successful";
}

经过

if(isset($_SESSION['account']) && $_SESSION['account'] == true){
     print"login successful";
}
于 2013-01-16T22:53:23.460 回答