Source Code for /public/06-retaining-state/login.php
<?php
session_start();
if( isset( $_GET['logout'] ) && $_GET['logout'] === 'true' ) {
session_destroy();
header( 'Location: login.php' );
die();
}
if( isset( $_POST['password'] ) ) {
if( $_POST['password'] === 'secret' ) {
$_SESSION['logged_in'] = true;
} else {
echo "<h2>Login failed</h2><p>Wrong password!</p>";
}
}
if( $_SESSION['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 {
?>
<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
}