What role do sessions play in managing user authentication in PHP?
Sessions play a crucial role in managing user authentication in PHP by storing user data securely on the server-side. This allows the server to identify and authenticate users across multiple requests without having to resend credentials each time. By using sessions, PHP developers can create a secure and seamless authentication process for their web applications.
<?php
session_start();
// Check if user is logged in
if(isset($_SESSION['user_id'])) {
// User is authenticated
echo 'Welcome, ' . $_SESSION['username'];
} else {
// Redirect to login page
header('Location: login.php');
exit();
}
?>