How does the PHP code snippet provided handle user authentication and logout?
The PHP code snippet provided uses session variables to handle user authentication. When a user logs in, their username is stored in a session variable. When the user logs out, the session is destroyed, effectively logging the user out.
<?php
session_start();
// Check if user is logged in
if(isset($_SESSION['username'])) {
echo 'Welcome, ' . $_SESSION['username'];
} else {
echo 'Please log in';
}
// User login
if(isset($_POST['login'])) {
$_SESSION['username'] = $_POST['username'];
}
// User logout
if(isset($_POST['logout'])) {
session_destroy();
header('Location: index.php');
}
?>
<form method="post">
<input type="text" name="username" placeholder="Username">
<input type="submit" name="login" value="Login">
<input type="submit" name="logout" value="Logout">
</form>
Related Questions
- What are the potential pitfalls of trying to execute multiple commands on a link click in PHP?
- How can PHP developers ensure that updating multiple records in a single form submission is efficient and error-free?
- What is the best practice for hiding a table row in PHP when there is no content in the database field?