How can PHP be integrated with .htaccess to improve website security and prevent unwanted access to certain folders?

To improve website security and prevent unwanted access to certain folders, PHP can be integrated with .htaccess by using PHP to handle authentication and authorization checks. This can be done by creating a PHP script that checks if a user is authorized to access a specific folder or file, and then using .htaccess to redirect requests to that script for authentication.

<?php
// Check if user is authorized to access the folder
if($_SERVER['PHP_AUTH_USER'] != 'admin' || $_SERVER['PHP_AUTH_PW'] != 'password'){
    header('WWW-Authenticate: Basic realm="Restricted Area"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Access Denied';
    exit;
}
// If user is authorized, continue to serve the requested file