How can PHP and .htaccess be used to protect directories containing sensitive files from unauthorized access?

To protect directories containing sensitive files from unauthorized access, you can use a combination of PHP and .htaccess. One approach is to create a PHP script that checks for proper authentication before allowing access to the files. Then, you can use .htaccess to restrict direct access to the files and only allow access through the PHP script.

<?php
// Check for proper authentication
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || 
    $_SERVER['PHP_AUTH_USER'] != 'username' || $_SERVER['PHP_AUTH_PW'] != 'password') {
    header('WWW-Authenticate: Basic realm="Restricted Area"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Access Denied';
    exit;
}

// Serve the file if authentication is successful
$file = 'path/to/sensitive/file.txt';
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Length: ' . filesize($file));
    readfile($file);
} else {
    echo 'File not found';
}
?>