How can the use of session variables improve the security of a PHP login script?

Session variables can improve the security of a PHP login script by storing sensitive user information on the server-side rather than in cookies or hidden form fields. This helps prevent tampering by users and reduces the risk of session hijacking. Additionally, session variables are automatically encrypted by PHP, adding an extra layer of security to the login process.

<?php
session_start();

// After successful login, store user information in session variables
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;

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