注销后必须刷新页面才能获得正确的代码

$loggedin = false; 
if ($_SESSION) { //user loggedin
    $loggedin = true;
    ...//get token
}
...
if($loggedin){
echo 'Hi '.$user['name'];
}
else{
echo 'Please log in';
}
...

I suppose the web page will display "please log in" when I log out. But it says "undefined $user variable at /src/myproject/index line 80". And after I refresh the page, it says "please log in".

What is the problem here? Thank you for your help.

From what I can tell from your pseudo code, you have some sort of key in the $_SESSION variable that says the user is logged in.

For demonstration, let's assume you do something like... After the user logs in, you assign $_SESSION['user'] = an array of user information. One of those keys is 'name'.

So, your code should look something like this

$loggedin = false;
if (isset($_SESSION['user'])) {
    $loggedin = true;
}

if ($loggedin) {
    echo "Hi " . $_SESSION['user']['name'];
}
else {
    echo "You are not logged in."
}

Please keep in mind this is just a solution for your code sample you posted. To do this properly, I would suggest the following changes:

  • create a class that handles authentication
  • create methods in that class to determine if the user is logged in or not
  • create methods to return the current logged in user.

This will make your code more extensible, reuseable and easier to follow in the future.

Best of luck.