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 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?