What are the advantages and disadvantages of using PHP headers for authentication compared to .htaccess/.htpasswd?

Using PHP headers for authentication allows for more flexibility and customization in terms of authentication logic and user management. However, it requires more manual coding and maintenance compared to using .htaccess/.htpasswd for basic authentication. .htaccess/.htpasswd is easier to set up and maintain, but it may lack the customization options available with PHP headers.

<?php
$username = 'admin';
$password = 'password';

if (!isset($_SERVER['PHP_AUTH_USER']) || $_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;
}

echo 'You are logged in!';
?>