How can PHP scripts be used to handle authentication and access control in web directories instead of using server-side methods like .htaccess?

Using PHP scripts for authentication and access control in web directories allows for more flexibility and customization compared to server-side methods like .htaccess. By using PHP, you can create login forms, validate user credentials, and manage access permissions dynamically based on user roles or conditions.

<?php
session_start();

// Check if user is logged in
if(!isset($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

// Check if user has the necessary access permissions
if($_SESSION['role'] !== 'admin') {
    echo 'You do not have permission to access this page.';
    exit;
}

// Your protected content here
echo 'Welcome, admin!';
?>