How can PHP code be optimized to handle login states more efficiently and securely?

To optimize PHP code for handling login states more efficiently and securely, it is recommended to use sessions to store user authentication information rather than storing sensitive data in cookies. This helps prevent unauthorized access to user data. Additionally, always use prepared statements when interacting with a database to prevent SQL injection attacks.

<?php
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])) {
    // User is logged in, perform necessary actions
} else {
    // User is not logged in, redirect to login page
    header("Location: login.php");
    exit();
}
?>