javascript php - 刷新页面后会话丢失
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24411588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php - session lost after refreshing page
提问by user43051
So I am developing a login system for my website and I would like to change the navigation bar when the user is logged but I can't get it to work because the session keeps getting lost after I refresh the page to update the navigation bar. This is what I got in my login.php script:
所以我正在为我的网站开发一个登录系统,我想在用户登录时更改导航栏,但我无法让它工作,因为在我刷新页面以更新导航栏后会话一直丢失。这是我在 login.php 脚本中得到的:
if ($loginNumRows == 1) {
echo 'true';
session_start();
$_SESSION['username'] = $loginRow['name'];
When this echoes 'true', the following javascript is loaded:
当这回显 'true' 时,将加载以下 javascript:
if (html == 'true') {
window.location.href = "index.php";
I tried with "location.reload(true);" and it is still the same. And in the main page, where the navigation bar is, I make the following check:
我试过“location.reload(true);” 它仍然是一样的。在导航栏所在的主页中,我进行了以下检查:
<?php if (isset($_SESSION))
{...}
However this always returns false. Any ideas what to do? Thanks!
然而,这总是返回false。任何想法该怎么做?谢谢!
采纳答案by Geseft
First of all, no need for javascript to redirect you to the index page. You can do it from PHP too:
首先,不需要 javascript 将您重定向到索引页面。您也可以从 PHP 中执行此操作:
header("Location: index.php");
So the login.php will look like this:
所以 login.php 看起来像这样:
if ($loginNumRows == 1) {
session_start();
$_SESSION['username'] = $loginRow['name'];
header("Location: index.php");
Note, that I have changed the order. As others I strongly recommend to put session start above all of your code.
请注意,我已经更改了顺序。与其他人一样,我强烈建议将 session start 置于所有代码之上。
And finally make sure that you have session started in the index.php file too(this should be also placed above all of your code ):
最后确保你也在 index.php 文件中启动了会话(这也应该放在你所有的代码之上):
session_start();
EDIT: If you want to stick with your javascript method ( witch I highly not recommend ), than your login.php code should look like this:
编辑:如果你想坚持你的 javascript 方法(女巫我强烈不推荐),那么你的 login.php 代码应该是这样的:
if ($loginNumRows == 1) {
session_start();
$_SESSION['username'] = $loginRow['name'];
echo 'true';
回答by MickyScion
Make sure that you have session_start();
at the top of all your scripts.
确保您session_start();
位于所有脚本的顶部。
回答by Tate Reynolds
As previously stated above, I would first put session_start() above all other code on the page, not in the conditional statement.
如前所述,我首先将 session_start() 放在页面上的所有其他代码之上,而不是放在条件语句中。