基于用户会话的重定向周期
我在重定向到页面时遇到问题。看起来它正在多次重定向自身。 我的标题中有
if(!isset($_SESSION)){
header("location:index.php");
exit();
}
。我的标题包含在我的索引页和其他任何地方。我知道,由于它位于标头中,因此它将被重定向到index.php,然后它会一遍又一遍地执行脚本,这给我带来了问题。
我如何防止它在重定向后立即停止执行此操作?或者是否有另一种方法来检查用户是否登录,如果没有,则转到index.php?
谢谢!
I have a problem with redirecting to a page. It seems like it is redirecting itself multiple times. I have
if(!isset($_SESSION)){
header("location:index.php");
exit();
}
in my header. and my header is included in my index page and everywhere else. I know that since it is in the header, it will be redirected to index.php then it will the script again and over and over which is giving me problems.
How would I prevent it to stop doing it right after redirecting? Or is there another way to check if user is logged in, if not, go to index.php?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您不应该检查 SESSION 数组本身是否已完整设置。您应该只分配一两个索引并检查它们。这样,您将永远无法逃脱重定向,因为您甚至无法分配 SESSION。
您需要分配类似
$_SESSION['authorized'] = TRUE; 的内容;
登录成功后,然后在每个页面上检查该索引是否已设置、是否为 TRUE,并进行相应操作。另外,您应该重定向到登录页面或类似的页面...您应该提供实际登录用户的可能性!当然,除非您的登录表单不在索引页面中,但您没有指定该信息...
此外,请记住在所有页面中首先调用
session_start()
您希望使用会话。You should not check for the SESSION array itself to be set in its entirety, for starter. You should just assign one or two indexes and check against them. In this way, you won't ever escape the redirect, since you're not even given the possibility to assign a SESSION..
You need to assign something like
$_SESSION['authorized'] = TRUE;
upon succesful login, and than, on every page, check if this index is set, is TRUE, and act accordingly.Also, you should redirect to a login page, or something like that...you should give the possibility to actually login to the user! Unless your login form isn't in the index page, of course, but you didn't specify that information...
Also, remember to call
session_start()
as the first thing in all your pages where you want Sessions to be used.您的
if
语句只是存在逻辑缺陷。如果会话处理已启动,则
$_SESSION
将存在。如果没有,则它不存在。
但这与您/用户是否使用会话无关。
所以
if
语句是没有用的。请阅读PHP 手册以了解会话在 PHP 中的工作原理。You have just a logic flaw with your
if
statement.If the session handling would have been started,
$_SESSION
would exists.If not, it does not exists.
But this is independent to whether you/the user makes use of a session or not.
So the
if
statement is useless. Please read the PHP Manual to learn how sessions work in PHP.我想通了,我知道我的标头中有一个 if 语句,所以当我尝试重定向到 index.php 时,我仍然有该 if 语句并且没有会话,我将重定向自己在永无休止的循环中。
我所做的只是为index.php 创建一个新标头
I figured it out, I knew that I had a if statement in my header, so while i'm trying to redirect to index.php, I still have that if statement and not having a session, i'm going to be redirecting myself in a never ending loop.
What I did is just created a new header for index.php