Search code examples
phpsessionunset

Unsetting PHP session variable doesnt display error message


I am trying to display an error message when there is a username-password mismatch. I set a php session variable if username and password dont match. Then i header back to the same page, with an if conditioned php statement to display an error if the variable is set. But when i unset the variable after error display, there is no error displayed on the page.

I have seen similar problems mentioned in this forum. But i seem to be doing everything right as suggested in questions.. Please help me out...

This is part of my code flow...

<?php
ob_start();
session_start();
.
.
if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
            $_SESSION['admin_user'] = $result['id'];
            header('Location: admin_user.php');
        } else {
            $_SESSION['user_found'] = 0;
            header('Location: index.php');
        }
.
.
//in html body
<?php
    if (isset($_SESSION['user_found'])){
        if($_SESSION['user_found'] == 0){
?>  
    <div>
    <p class = "bg-danger text-danger">Username Password Mismatch</p>
    </div>

<?php   
unset($_SESSION['user_found']);
        } 
    }

?>

Now, if unset is removed..it works fine. If it is there, there is no display of error message.


Solution

  • Try not reloading the same page.. remove the header redirect.

    if ($result = $sth->fetch(PDO::FETCH_ASSOC)){
                $_SESSION['admin_user'] = $result['id'];
                header('Location: admin_user.php');
            } else {
                $_SESSION['user_found'] = 0;
                //header('Location: index.php');
            }