What are the best practices for handling authentication and authorization in PHP to ensure secure access to restricted pages?

To ensure secure access to restricted pages in PHP, it is important to handle authentication and authorization properly. This involves verifying the user's identity through login credentials and then checking their permissions to access specific pages or resources. Best practices include using secure password hashing, implementing session management to track authenticated users, and validating user input to prevent common security vulnerabilities like SQL injection or cross-site scripting.

<?php
// Start session
session_start();

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

// Check user's permissions to access the page
if ($_SESSION['role'] !== 'admin') {
    // Redirect to unauthorized page
    header("Location: unauthorized.php");
    exit;
}
?>