What best practices should be followed when using PHP to manage page access and user sessions on a website?

When managing page access and user sessions in PHP, it is important to follow best practices to ensure security and efficiency. This includes properly validating user input, using secure session handling techniques, and implementing access control mechanisms to restrict unauthorized access to certain pages.

// Start a secure session
session_start();

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

// Check user role for access control
if ($_SESSION['role'] !== 'admin') {
    // Redirect to unauthorized page if user does not have admin role
    header("Location: unauthorized.php");
    exit;
}