1

I am just learning php and have an assignment to create a dynamic login/logout page using sessions. I have created it, but the logout script is not working. If I login and then logout, the button still says logout and the welcome message with my name appears as if the session is not being terminated. I have tried everything I can think of to fix this and nothing works. My question is: how can I fix my code so that the logout script works? If anyone can help me figure this out, I would sure appreciate it. I have a template page, which is where I have placed the following code:

<!-- Contents of template.php -->
<?php
if(isset($_POST['logout'])) {
    $msg = 'You are logged out.';
    foreach ($_SESSION as $field => $value) {
        unset($_SESSION[$field]);
    }
    session_destroy();
    header("Location: login.php?msg=$msg");
    exit;
}
if(isset($_SESSION['memberID'])) {
    $loginButton = '<button class="btn btn-outline-primary" name="logout" type="submit">Logout</button>';

} else {
    $loginButton = '<button class="btn btn-outline-primary" name="login" type="submit">Login</button>';
}

if(isset($_COOKIE['firstname'])){
    $firstname = $_COOKIE['firstname'];
} else {
    $firstname = 'Guest';   
}
echo "<p>Welcome back, $firstname.</p>";
?>

<!doctype html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title><?php echo $pageTitle; ?></title>

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css">   
  </head>
  <body>
    <div class="container"> 
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <a class="navbar-brand" href="#"></a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data- target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle 
navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
    <div class="navbar-nav">
      <a class="nav-item nav-link active" href="index.php">Home <span class="sr-only">(current)</span></a>
      <a class="nav-item nav-link" href="form.php">Order Form</a>
      <a class="nav-item nav-link" href="invoice.php">Invoice</a>
        <form action="login.php" class="form-inline">
            <?php echo $loginButton ?>
        </form>
  
    </div>
  </div>
</nav>

<?php echo $pageContent; ?>

</div>
  </body>

</html>

The config page which I include on the other pages just has session_start(); at the top between the php tags. The login page has the following code:

    <?php
    include 'config.php';
    if(!$conn) {
    echo "Failed to connect to the database: " .mysqli_connect_error();
    }
    $pageTitle = "Login Page";
    $pageContent = NULL;
    $msg = NULL;
    $invalidUser = NULL;
    $invalidPassword = NULL;

    if (filter_has_var(INPUT_POST, 'login')) {
        $username = strip_tags(filter_input(INPUT_POST, 'username'));
        $passwordSubmit = trim(filter_input(INPUT_POST, 'password'));
        $valid = TRUE;
    
        if ($username == NULL) {
            $invalidUser = '<span class="error">Required Field</span>';
            $valid = FALSE;
        }
    
        if ($passwordSubmit == NULL) {
            $invalidPassword = '<span class="error">Required Field</span>';
                $valid = FALSE;
        }
    
    if ($valid) {
        $stmt = $conn->stmt_init();
        if  ($stmt->prepare("SELECT `memberID`, `password` FROM `membership` WHERE `username` = ?")) {
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($memberID, $password);
            $stmt->fetch();
            $stmt->free_result();
            $stmt->close();
        
        } else {
            $msg = <<<HERE
            <h3 class="error">We could not find you in the system.  New users must register before gaining access to the site.  If you forgot your login, please use the Password Recover Tool.</h3>
HERE;
        }

        if (password_verify($passwordSubmit, $password)) {
            $stmt = $conn->stmt_init();
            if ($stmt->prepare("SELECT `firstname`, `lastname`, `email` FROM `membership` WHERE `memberID` = ?")) {
                $stmt->bind_param("i", $memberID);
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result($firstname, $lastname, $email);
            
                if ($stmt->num_rows == 1) {
                    $stmt->fetch();
                    $_SESSION['memberID'] = $memberID;
                    //$_SESSION['firstname'] = $firstname;
                    //$_SESSION['lastname'] = $lastname;
                    //$_SESSION['email'] = $email;
                    //$_SESSION['loggedIn'] = TRUE;
                
                    setcookie("firstname", $firstname, time()+(3600*3));
                    setcookie("lastname", $lastname, time()+(3600*3));
                
                    $stmt->close();
                
                    header("Location: profile.php");
                    exit;
                
                } else {
                    $msg = <<<HERE
                    <h3 class="error">We could access your login records.</h3>
HERE;
                }
            
            } else {
                    $msg = <<<HERE
                    <h3 class="error">We could not find your information.</h3>
HERE;
            }
        } else {
            $msg = <<<HERE
            <h3 class="error">We could not find you in the system.  New users must register before gaining access to the site.  If you forgot your login, please use the Password Recovery Tool.</h3>
HERE;
    }
    }
    }

    $pageContent .= <<<HERE
    <section class="container">
    $msg
    <form action="login.php" method="post">
        <div class="form-group">
        <label>Username $invalidUser</label>
        <input type="text" class="form-control" id="username" name="username" required />
        </div>
        <div class="form-group">
        <label>Password $invalidPassword</label>
        <input type="password" class="form-control" id="password" name="password" required />
    
        </div>
        <input type="submit" name="login" value="Login" class="btn btn-primary">
        </form>
        </section>
HERE;

    $pageContent .= "<pre>";
    $pageContent .= "</pre>";
    $pageTitle = "Login Page";
    
    include 'template.php';
    ?>
meohmy
  • 11
  • 2
  • 1
    This might help: https://stackoverflow.com/a/3512570/1772933 – Kinglish Apr 29 '21 at 20:48
  • What is the question exactly? Please update your question to be more specific and turn it into an actual question. – Jacob Bruinsma Apr 29 '21 at 20:51
  • 1
    **WARNING**: Writing an access control layer is not easy and there are many opportunities to get it severely wrong. Any modern [development framework](https://www.cloudways.com/blog/best-php-frameworks/) like [Laravel](http://laravel.com/) comes with an [authentication system](https://laravel.com/docs/master/authentication) built-in. – tadman Apr 29 '21 at 21:40
  • @Staplerfahrer I edited to clarify. Basically my question is, what can I change in my code to make sure the logout script works? Currently, it is not working. I can hit logout, but it still says I am logged in. I don't think my session is terminating. – meohmy Apr 30 '21 at 19:53

0 Answers0