PHP 中的会话 ID 和变量
我有一个登录页面,一旦用户成功登录,它就会回显指向其个人页面的链接。当该页面加载时,我希望它检查用户是否有权访问该页面,这样就不会有人尝试在网址中输入 www.mywebsite.com/bob.php 。我尝试使用 cookie 来发送用户信息,但我意识到在将 html 写入页面后就无法使用 cookie。有谁知道一种有效且相当简单的方法吗?谢谢
I have a login page where once a user is logged in successfully it echos a link to their personal page. When that page loads I want it to check if the user has access to it so someone doesn't try to just type in www.mywebsite.com/bob.php in the url. I tried to use a cookie to send the user info but I realized you can't use cookies after html has been written to the page. Does anyone know an efficient way to do this that is also fairly simple? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用户登录后,将其 id 分配给会话变量:
在受保护的页面上,检查用户是否设置了 $_SESSION["userid"] 变量:
After the user logs in, assign his id to a session variable:
On the protected page, check if the user has a $_SESSION["userid"] variable set:
当输出已经发送到浏览器时,您确实无法设置 cookie。一个有用的技巧是使用输出缓冲。基本上,您的代码以调用
ob_start()
开始,并以ob_end_flush()
结束。现在,您可以在代码中的任意位置设置 cookie(以及任何 HTML 标头)。It is true that you cannot set cookies when output has already been sent to the browser. A useful trick is to use output buffering. Basically, you begin your code with a call to
ob_start()
and end it withob_end_flush()
. Now you can set cookies (and any HTML header) wherever you want in your code.