How can you monitor unauthorized access attempts to directories/files protected by HTAccess using PHP?

Unauthorized access attempts to directories/files protected by HTAccess can be monitored by checking the HTTP status code returned when a user tries to access the protected resource. This can be done by using PHP to send a HEAD request to the resource and checking the response code. If the status code is 401 (Unauthorized), it means that the access attempt was blocked by HTAccess.

<?php
$url = 'https://example.com/protected-directory/file.txt';
$options = array(
    'http' => array(
        'method' => 'HEAD',
        'ignore_errors' => true
    )
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if(strpos($http_response_header[0], '401') !== false) {
    echo 'Unauthorized access attempt detected!';
}
?>