How can using sessions instead of cookies improve the security of a PHP login system and prevent potential vulnerabilities?

Using sessions instead of cookies can improve the security of a PHP login system by storing sensitive information on the server side rather than on the client side. This prevents potential vulnerabilities such as cookie theft or manipulation. Sessions also provide more control over the expiration and management of user data.

<?php
session_start();

// Check login credentials
if($username == $valid_username && $password == $valid_password){
    $_SESSION['logged_in'] = true;
    $_SESSION['username'] = $username;
    // Redirect to secure page
    header("Location: secure_page.php");
    exit();
} else {
    // Display error message
    echo "Invalid username or password";
}
?>