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
- How can the layout be changed to display content within the same area instead of below it?
- What are best practices for including database query results in external PHP files for display?
- How can debugging techniques like the one mentioned in the provided link help in resolving PHP code issues related to database queries?