虽然您可以散列 user_id 和 secret_key,但截获此 cookie 的任何人都可以登录您的应用程序。除此之外,您还可以让您的记住我的 cookie 很快过时。没有人喜欢陈旧的饼干。
您可以将每个用户上次访问的时间戳存储在您的数据库和 cookie 中。每次您读取 cookie 以使用户登录时,您都会检查两个时间戳是否匹配。如果他们不这样做,则拒绝该用户。如果有,请更新时间戳。
使用此方法,任何时候您的用户返回您的网站,所有旧的 cookie 都会过时。截获 cookie 的黑客现在拥有一个毫无价值的陈旧 cookie,因为他不知道当前 cookie 中的确切时间戳。当然,黑客可以在用户重新登录之前尽可能多地使用新的 cookie。
//check for cookie
if(isset($_COOKIE['remember_me'])) {
// get hash and time stamp from cookie
$hash = substr($_COOKIE['remember_me'],0,40);
$last_visit = substr($_COOKIE['remember_me'],41);
// query your db with $hash and $last_visit
// if hash and time stamp match up
// log in
// store the current time stamp in a variable to use for both
$time = date("Y-m-d H:i:s");
// update the time stamp in your cookie
$cookie = $pass . "-" . $time;
setcookie('remember_me', $cookie, time()+60*60*24*100, '/');
// update the time_stamp in your database
else {
// remove the remember me cookie
setcookie('remember_me', '', time()-42000, '/')
}
这种方法提供了少量的安全性,当然应该与其他答案中提出的方法一起使用。散列密钥应存储在 cookie 中。记住我的 cookie 不能完全安全,因此对高度敏感数据或应用程序功能的任何其他访问都需要重新输入密码。
我还建议将您的 cookie 命名为“remember_me”以外的其他名称,以使其更难找到。虽然它不会增加太多安全性(如果有的话),但将您的 cookie 命名为“ht33424”所花费的时间与将其命名为“remember_me”或“hack_me”的时间一样长。