PHP setcookie 不工作
看起来它应该可以工作:
if ($_POST['stayloggedin'] == 'stayloggedin') {
setcookie("user", $_POST['mail'], time()+7*24*60*60, '/', 'subdomain.example.com', false, true);
setcookie("hash", md5(sha1(md5($_POST['pw']))), time()+7*24*60*60, '/', 'subdomain.example.com', false, true);
}
header("Location: /");
exit();
我已经将 ob_start() 放在代码之上,所以这不应该是重点。
Looks like it should be working:
if ($_POST['stayloggedin'] == 'stayloggedin') {
setcookie("user", $_POST['mail'], time()+7*24*60*60, '/', 'subdomain.example.com', false, true);
setcookie("hash", md5(sha1(md5($_POST['pw']))), time()+7*24*60*60, '/', 'subdomain.example.com', false, true);
}
header("Location: /");
exit();
I have put ob_start() on top of the code, so that shouldn't be the point.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
确保您的 php.ini 文件允许 cookie。此外,您不应该将敏感数据存储在 cookie 或会话变量中。
建议:
相反,存储一个唯一的 ID,然后查询数据库以获取用户名和密码等详细信息。你只是要求以你正在做的方式被黑客攻击。
并不是消极的,只是一个有用的预防技巧。
make sure your php.ini file allows cookies.. Also, you should NEVER store sensitive data in a cookie or a session variable.
Suggestion:
store a unique id instead, then query the database for details like usernames and passwords. You are just asking to get hacked doing it the way you are doing it.
Not to be negative, just a helpful preventative tip.
确保在调用
setcookie()
函数之前没有向浏览器发送任何输出。ob_start()
应该会停止“output beforesetcookie()
”错误,但它可能无法正确实现。Make sure that you aren't sending any output to the browser before the
setcookie()
function is called.ob_start()
should stop the "output beforesetcookie()
" error, but it might not be implemented correctly.迈克是对的。在输出任何内容之前,您都会离开页面并终止 PHP 执行。 ob_start() 实际上是问题所在:它打开输出缓冲区(而不是实际发送数据)。如果您想要发送某些内容,则必须刷新缓冲区(使用 ob_end_flush())或等待 PHP 脚本正常结束。因此,在您的情况下,根本不会发送 cookie。
mike is right. You are both leaving the page and killing the PHP execution before you even ouput anything.
ob_start()
is in fact the problem: it opens the output buffer (instead of actually sending the data). If you want something to be sent, you have either to flush the buffer (withob_end_flush()
) or to wait for the normal end of the PHP script. So in your case, the cookies are not sent at all.看看该代码片段,我会说问题是 cookie 永远不会发送到用户的浏览器。 Cookie 存储在客户端,而不是服务器端;您正在创建两个新脚本,但随后立即调用 exit() ,这将在从服务器向用户发送任何响应之前终止 PHP 脚本。
Looking at that code snippet I'd say the problem is that the cookie is never sent to the user's browser. Cookies are stored clientside, not serverside; you're creating two new ones but then immediately calling exit() which kills the PHP script before any response is dispatched from the server to the user.
试试这个
Try this