如何(安全地)存储cookie并在用户重新打开浏览器时保持用户登录

时间:2011-12-26 15:56:03

标签: php html

如何在仍然能够访问该密码的同时将用户密码安全地存储在cookie中?我有一个cookie存储密码的用户名和sha1版本但是当我尝试检索它们时,我得到(如预期的)用户名和密码的sha1版本,而不是密码本身。 THX!

<!DOCTYPE html>
<html>
  <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
  </head>
<body>

<form id='my_login' name='my_login' action='<?php htmlentities($_SERVER['PHP_SELF'])?>' method='post' accept-charset='UTF-8'>
<input type='hidden' name='submitted' id='submitted' value='1'/>
 <label for='username'>Username: </label>
 <input id='username' type='text' name='username' value='<?php if(isset($_COOKIE['username'])) echo htmlentities($_COOKIE['username']); ?>'/>
 <br/>
 <label for='username'>Password: </label>
 <input id='password' type='password' name='password' value='<?php if(isset($_COOKIE['password'])) echo htmlentities($_COOKIE['password']); ?>'/>
 <br/>
  <label for "set_cookie">Remember Me</label>
 <input type="checkbox" name="set_cookie" id="set_cookie" value="1"/>
 <button id='submit' type='submit' name='submit'>login</button>
   </form>

  </body>
  <html>

2 个答案:

答案 0 :(得分:8)

  

如何在cookie中安全地存储用户密码

切勿在本地存储用户密码。即使使用目前被认为是安全的加密,您也会面临巨大的潜在安全漏洞,因为您正在为可能的攻击者传播数据,而不是许多客户端计算机。

为用户提供带有随机会话ID的长期Cookie。给该会话将来一个到期时间(无限期存储它不是一个好主意。许多网站将其限制为30天。)让该ID在您的服务器上自动登录用户。

答案 1 :(得分:0)

此外,当您使用php setcookie时,请确保将最后一个参数httponly添加到true。

  

的HttpOnly

     

当为TRUE时,cookie只能通过HTTP协议访问。这意味着脚本语言(例如JavaScript)无法访问cookie。有人建议这种设置可以通过XSS攻击有效地帮助减少身份盗用(尽管并非所有浏览器都支持),但这种说法经常受到质疑。在PHP 5.2.0中添加。 TRUE或FALSE

来源:PHP setcookie

这将减少cookie被JavaScript劫持。

如果您有这种能力,您还可以设置secure标志,仅通过https发送cookie。