How can PHP scripts access and interact with .htpasswd files generated by Apache servers for user authentication?

PHP scripts can access and interact with .htpasswd files generated by Apache servers for user authentication by using PHP's built-in functions for password hashing and verification. One common approach is to read the .htpasswd file, parse the username and hashed password, and then compare it with the user input using password_verify() function.

<?php
$htpasswd_file = '.htpasswd';
$username = 'example_user';
$password = 'example_password';

$htpasswd_contents = file_get_contents($htpasswd_file);
$lines = explode("\n", $htpasswd_contents);

foreach ($lines as $line) {
    list($user, $hash) = explode(':', $line);
    if ($user === $username && password_verify($password, trim($hash))) {
        echo 'Authentication successful!';
        break;
    }
}
?>