Source Code for /public/06-retaining-state/login.php

<?php
// Start the session:
session_start();

// Check if the user has requested to log out (?logout=true):
if( isset( $_GET['logout'] ) && $_GET['logout'] === 'true' ) {
  // Log the user out:
  session_destroy();
  // Refresh the page so we start a new session!
  header( 'Location: login.php' );
  die();
}

// Check if a password was submitted ($_POST['password']):
 if( isset( $_POST['password'] ) ) {
  // Check if the password is correct:
  if( $_POST['password'] === 'secret' ) {
    // Password is correct: log the user in!
    $_SESSION['logged_in'] = true;
  } else {
    // Password is incorrect: show an error message:
    echo "<h2>Login failed</h2><p>Wrong password!</p>";
  }
 }

// Check if the user is logged in:
if( $_SESSION['logged_in'] ) {
  // They are logged-in!
  ?>
  <h1>You're logged in!</h1>
  <ul>
    <li>
      <a href="members.php">Go to the members area</a>
    </li>
    <li>
      <a href="login.php?logout=true">Log out</a>
    </li>
  </ul>
  <?php
} else {
  // They're not logged in!
  ?>
  <h1>Login</h1>
  <p>
    Once you log in, you'll be able to access
    <a href="members.php">the members area</a>.
  </p>
  <form method="post" action="login.php">
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" autofocus>
    <button type="submit">Login</button>
  </form>
  <p>
    <small>
      🤫 Shh! The password is "secret".
    </small>
  </p>
  <?php
}