【问题标题】:PHP- Fix problem where sessions only take effect after refreshingPHP- 修复会话刷新后才生效的问题
【发布时间】:2011-09-27 21:14:47
【问题描述】:

请查看this Stackoverflow 帖子。

我和 bob_cobb 有同样的 PHP 问题。这是布拉德·克里斯特的回答:

操作顺序。

将您的会话创建和 有效性检验 页面顶部,所以其余的 页面可以做出判断调用关闭 存在 $_SESSION['username']

(您可能正在尝试验证 它们在内容区域内,因此您的 “yay”或“ney”消息出现在 文档的所需部分。 漂亮,是的,但整个上半部分 页面看不到它是 [潜在地] 一个有效的会话。)

他基本上是在说 session_start() 和检查会话变量的条件应该在顶部,以便页面的其余部分可以基于此操作。

但是,我的会话检查位于页面顶部。

<?php
session_start();

if ($_SESSION['username']) 
//User is already logged in, echo the log out button.
...    

else 
//User is not logged in, echo the log in form & button.
...    

//Login form validation if user is not logged in and submitted form.
//At the end, create session variable ($_SESSION['username'])

//Destroy session if user pressed log out button.
session_destroy();
?>

一切正常,但是,与另一个问题的海报一样,我必须刷新我的页面,才能执行 top 脚本(检查脚本对于 $_SESSION['username'])。

这是为什么呢?

【问题讨论】:

  • @user805556,到底是什么问题?我们需要更多信息来帮助您。首先解释$_SESSION 中的内容及其设置位置。
  • 我以为我把问题说得很清楚了。就像其他人一样,我应该读取会话变量的脚本只有在刷新后才会执行。 $_SESSION 访问文档的会话,并在用户登录时设置。我将添加它。
  • @AlienWebguy 我不知道人们居然如此认真地对待这些观点......

标签: php forms session post header


【解决方案1】:

在整个控制流程完成之前不要回显任何内容。我的意思是你应该努力将逻辑与显示分开(更好的是:使用像Model-View-Controller 这样的模式)。在你的情况下,也许你可以这样做:

<?php
/* Place all your control logic at the beginning.
   Do not echo anything in this block. */

session_start();

if ($_SESSION['username']) {
  $loggedin = true;
} else {
  $loggedin = false;
  ...    

  //Login form validation if user is not logged in and submitted form.
  //If login succeeded, set $loggedin to true.
  //At the end, create session variable.
}

//Destroy session if user pressed log out button.
  session_destroy();

/* Only display logic below, we do not change any state here */

if($loggedin) {
  echo logout button
} else {
  echo login form
}
?>

【讨论】:

  • 它有效,我只是忘记将 $loggedin 设置为 true 之前。非常感谢。
【解决方案2】:

答案很简单。用户注册后无需取消会话。 试试这个

<?php
session_start();

if ($_SESSION['username']) 
//User is already logged in, echo the log out button.
...    

else 
//User is not logged in, echo the log in form & button.
...    

//Login form validation if user is not logged in and submitted form.
//At the end, create session variable.

//Destroy session if user pressed log out button.
//session_destroy();
--- do a redirect or a refresh here .... 
?>

【讨论】:

  • 如何进行重定向或刷新?我认为这只有在标题中才有可能。你的意思是通过Javascript?不行,我试过了。
  • 他重定向的地方,你使用PHP的header()
  • 是的,但是我不能把它放在页面底部。我认为标题必须放在顶部。
猜你喜欢
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多