What are the best practices for implementing a centralized structure for handling user authentication and page access in PHP?

Implementing a centralized structure for handling user authentication and page access in PHP helps to ensure consistent security measures across your application. This can be achieved by creating a separate PHP file that contains functions for user authentication, such as login, logout, and checking user roles, and using these functions throughout your application.

// auth.php

session_start();

function login($username, $password) {
    // Validate username and password
    // Set session variables if authentication is successful
}

function logout() {
    // Unset session variables and destroy session
}

function checkUserRole($role) {
    // Check if the user has the specified role
}

// index.php

include 'auth.php';

if(isset($_POST['login'])) {
    login($_POST['username'], $_POST['password']);
}

if(isset($_GET['logout'])) {
    logout();
}

if(!checkUserRole('admin')) {
    // Redirect to unauthorized page
}