How can PHP_AUTH_USER and $_SERVER['PHP_AUTH_PW'] be utilized for user authentication in PHP?

PHP_AUTH_USER and $_SERVER['PHP_AUTH_PW'] are server variables that can be utilized for basic HTTP authentication in PHP. These variables store the username and password entered by the user when prompted by the browser. You can use these variables to authenticate users before granting access to certain parts of your website.

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
    header('WWW-Authenticate: Basic realm="My Website"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Authentication required.';
    exit;
}

$valid_username = 'admin';
$valid_password = 'password';

if ($_SERVER['PHP_AUTH_USER'] != $valid_username || $_SERVER['PHP_AUTH_PW'] != $valid_password) {
    header('WWW-Authenticate: Basic realm="My Website"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Invalid credentials.';
    exit;
}

// User is authenticated, continue with the rest of your code