PHP- Fix problem where sessions only take effect after refreshing
Please review this Stackoverflow post.
I have the same PHP problem as bob_cobb. Here's Brad Chrisite's answer:
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开发者_Go百科 top-half of the page can't see that it's [potentially] a valid session.)
He is basically saying that session_start() and the conditionals that check for session variables should be at the top, so that the rest of the page could act based upon that.
However, my session-check is at the top of the page.
<?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();
?>
Everything works fine, but, as with the poster of the other question, I have to refresh my page, to get the top script executed (the script that checks for $_SESSION['username']).
Why is that?
Do not echo anything before your entire control flow is finished. What I mean by this is that you should work to separate logic from display (even better: use a pattern like Model-View-Controller). In your case, maybe you can do something like this:
<?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
}
?>
The answer is simple. You need not unset the session after making the user registration. Try this
<?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 ....
?>
精彩评论