How can one integrate .htaccess authentication with PHP scripts for user authentication?
To integrate .htaccess authentication with PHP scripts for user authentication, you can use PHP to check if the user is authenticated by checking the $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] variables set by .htaccess. If these variables are set, you can then perform any additional user authentication logic within your PHP script.
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authentication required.';
exit;
} else {
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
// Perform additional authentication logic here, such as checking against a database of users
if ($authenticated) {
echo 'Welcome, ' . $username . '!';
} else {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Invalid credentials.';
exit;
}
}