在 PHP 登录期间,我应该如何处理“记住我”选项


How should I handle a 'Remember me' option during PHP login?

我正在用PHP构建一个网站,但我不确定如何处理用户在登录过程中的"记住我"选项。

不确定是否将用户名和密码保存在 JavaScript 存储中,并在再次提示用户登录过程时自动填充它(我怀疑此选项,因为它会非常不安全)或以某种方式使 PHP 会话永不过期(这甚至可能吗?

以下是当前的登录脚本:

<?php
include_once("connection.php");
session_start();
if (!empty($_POST)) {
    $sth = $dbh->prepare("SELECT customer_number FROM customers WHERE username = :username AND password = :password");
    $sth->bindValue(':username', $_POST['username'], PDO::PARAM_STR);
    $sth->bindValue(':password', $_POST['password'], PDO::PARAM_STR);
    $sth->execute();
    $result = $sth->fetchAll();
    if (!empty($result)) {
        $_SESSION['customer_number'] = $result[0]['0'];
        header("Location: /");
    }
    else {
        header("Location: /");
    }      
}
?>

"记住我"选项可通过$_POST['remember']访问。

当用户在选中Remember Me选项后登录时,创建一个带有tokenidcookie

您可以遵循的步骤:

1)创建一个随机令牌ID并将其与userIdexpiration time一起存储在数据库中。

2) 将此cookie idtokenid存储在用户登录时cookie中。

认证:

如果找到持久cookie,请检查该 cookie 的记录是否存在,并检查令牌是否与数据库中的令牌匹配

还要检查过期时间和UserId

另请查看有关如何从此处实施它的最佳实践

还有一个关于如何实现此功能的很好的SO问题

尝试以下代码:

if (isset($_POST['remember']) and $_POST['remember'] == "Yes") {
        setcookie("username", $_POST['username'], time() + 60 * 60 * 24 * 100, "/");
        setcookie("password", $_POST['password'], time() + 60 * 60 * 24 * 100, "/");
} else {
        setcookie("username", "", time() + 60 * 60 * 24 * 100, "/");
        setcookie("password", "", time() + 60 * 60 * 24 * 100, "/");
}

您将被设置一个cookie。会话是服务器,将在服务器关闭时删除(关闭浏览器)

setcookie("customer_number", $result[0]['0'], time() + 60, "/");

时间是一分钟,"/"是所有页面。

<?php
if(isSet($cookie_name))
{
    // Check if the cookie exists
if(isSet($_COOKIE[$cookie_name]))
    {
    parse_str($_COOKIE[$cookie_name]);
    // Make a verification
    if(($usr == $_POST['username']) && ($hash == md5($_POST['password'])))
        {
        // Register the session
        $_SESSION['username'] = $_POST['username'];
        }
    }
}
?>

一些有用的答案:如何实现记住我功能?

http://www.downwithdesign.com/web-development-tutorials/adding-remember-feature-php-login-script/

http://www.bitrepository.com/php-autologin.html