What are the best practices for implementing sessions in PHP to control user access to certain pages?

To control user access to certain pages in PHP, it is recommended to use sessions to track and manage user authentication and authorization. By storing user login information in a session variable, you can restrict access to specific pages based on the user's login status or role.

// Start the session
session_start();

// Check if the 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['user_role'] != 'admin') {
    // Redirect to unauthorized page if user role is not admin
    header("Location: unauthorized.php");
    exit();
}

// Access to restricted page content here
echo "Welcome, Admin!";