How can using $_SESSION variables improve the security and functionality of a login system in PHP?

Using $_SESSION variables can improve the security and functionality of a login system in PHP by storing sensitive user information on the server side, rather than in cookies or hidden form fields. This helps prevent unauthorized access to user data and reduces the risk of session hijacking. Additionally, $_SESSION variables can be used to store user authentication status, making it easier to manage user sessions and restrict access to certain pages or features.

// Start or resume a session
session_start();

// Set session variables upon successful login
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;

// Check if user is logged in on restricted pages
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}