What are the best practices for handling user sessions in PHP to prevent unauthorized access to protected pages?

One of the best practices for handling user sessions in PHP to prevent unauthorized access to protected pages is to use session variables to store user authentication information. You can set a session variable upon successful login and check for its existence on protected pages to ensure that only authenticated users can access them.

// Start the session
session_start();

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

// Protected page content here