What role do sessions play in a PHP login script and why are they important?

Sessions play a crucial role in a PHP login script as they help to keep track of a user's authentication status across multiple pages. They store important information such as the user's username or ID securely on the server, allowing the user to navigate through the website without having to re-enter their credentials on every page. Sessions are important for maintaining user authentication and ensuring that sensitive information is not exposed to unauthorized users.

// Start a session
session_start();

// Store user information in session variables upon successful login
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;

// Redirect the user to a secure page after login
header('Location: secure_page.php');
exit();