gpt4 book ai didi

PHP- 修复 session 刷新后才生效的问题

转载 作者:行者123 更新时间:2023-12-04 06:21:01 24 4
gpt4 key购买 nike

请查看 this Stackoverflow 帖子。

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

Order of operations.

Place your session creation and test-for-validity check at the very top of the page so the rest of the page can make judgment calls off the existence of $_SESSION['username']

(Chances are you're trying to validate them inside the content area so your "yay" or "ney" message appears in the desired section of the document. Pretty, yes, but the whole top-half of the page can't see that it's [potentially] a valid session.)



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

但是,我的 session 检查 在页面顶部。
<?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();
?>

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

这是为什么?

最佳答案

在整个控制流完成之前不要回显任何内容。我的意思是你应该努力将逻辑与显示分开(更好的是:使用像 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
}
?>

关于PHP- 修复 session 刷新后才生效的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6567388/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com