1
votes

I want to show my logout form (containing logout button) when user is logged in and hide otherwise. I use this code:

<?php
if(isset($_SESSION['logged_in'])) {
//show logout form
?>

Problem in steps:

  1. User gets on page and fills info in login form
  2. Login form is submitted (controlled with hidden input), on button click
  3. Login input value is compared with database values
  4. If input values are correct; $_SESSION['logged_in'] = true
  5. echo 'You are logged in!'
  6. The page gets refreshed (automatically done after form submit); 'You are logged' in is shown, but the logout form is not
  7. Now I have to refresh the page myself; The logout form is shown

Same thing happens on logging out. Logout form (and login form) only hides/shows when I refresh the page myself.

Any possible solutions?

2

2 Answers

1
votes

After some testing and diving into php.net, I found the answer myself. For anyone who would be confronted with the same kind of problem:

  1. Include your html AFTER you php code; otherwise code will not effect html after first page refresh
  2. set with each cookie its live time. When no time filled in, cookie will get destroyed when session ends.

    setcookie('username', $username); //NOT (no point at all in making this)
    setcookie('username', $username, time()+ 60*60*24*30 ); //YES
    
  3. session_destroy() destroys the session but does not unset any session variables. So for example when logging out, you have to unset session:

    unset($_SESSION['logged_in']);
    session_destroy(); //and then destroy session if needed
    
0
votes

Try this pattern Post/Redirect/Get.

You simply post the login, do your logic and redirect the user to landing page (or wherever they were before logging in). This way it is assured that the users browser is refreshed (hence he\she is redirected to another page)