我正在用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']
访问“记住我”选项。
答案 0 :(得分:2)
如果用户在选中Remember Me
选项后登录,请使用cookie
tokenid
您可以遵循的步骤:
1)创建一个随机令牌ID,并将其与userId
和expiration time
一起存储在数据库中。
2)当用户登录时,将此cookie id
和tokenid
存储在cookie
中。
<强>认证强>
如果找到持久cookie
,请检查该cookie的记录是否存在,并检查该令牌是否与数据库中的令牌匹配
同时检查到期时间和UserId
另请参阅 HERE
,了解如何实施该方法的最佳做法如何实施此功能还有一个很好的 SO Question
答案 1 :(得分:1)
尝试以下代码:
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, "/");
}
答案 2 :(得分:0)
您将设置Cookie 。 会话是服务器,将在服务器中删除(关闭浏览器)
setcookie("customer_number", $result[0]['0'], time() + 60, "/");
时间是一分钟,“/”是所有页面。
答案 3 :(得分:0)
<?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'];
}
}
}
?>
一些有用的答案: How to implement remember me feature?
http://www.downwithdesign.com/web-development-tutorials/adding-remember-feature-php-login-script/