How can PHP be used to handle HTTP authentication without relying on .htaccess files?

When handling HTTP authentication in PHP without relying on .htaccess files, you can use PHP's built-in functions to prompt users for credentials and authenticate them before allowing access to a specific page. This can be achieved by sending the appropriate headers and checking the provided credentials against a predefined list or database.

<?php
$valid_username = 'admin';
$valid_password = 'password';

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) ||
    $_SERVER['PHP_AUTH_USER'] != $valid_username || $_SERVER['PHP_AUTH_PW'] != $valid_password) {
    header('WWW-Authenticate: Basic realm="Restricted Area"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Access Denied';
    exit;
}

echo 'You are logged in!';
?>