What are the best practices for handling user authentication and access control in PHP?

User authentication and access control are critical components of web applications to ensure that only authorized users can access certain features or resources. Best practices for handling user authentication in PHP include using secure password hashing algorithms like bcrypt, implementing session management to keep track of authenticated users, and using role-based access control to restrict access to specific parts of the application based on user roles.

// Example of user authentication and access control in PHP

// Step 1: Authenticate user
if ($_POST['username'] == 'admin' && password_verify($_POST['password'], $hashedPassword)) {
    // User is authenticated, set session variables
    $_SESSION['user'] = 'admin';
} else {
    // Authentication failed, redirect to login page
    header('Location: login.php');
    exit();
}

// Step 2: Check user access control
if ($_SESSION['user'] !== 'admin') {
    // User does not have access, redirect to unauthorized page
    header('Location: unauthorized.php');
    exit();
}

// Step 3: User has access, continue with application logic
echo "Welcome, admin!";