Skip to content

Instantly share code, notes, and snippets.

@agwells
Forked from rchrd2/test-php-basic-auth.php
Last active January 19, 2020 20:56
Show Gist options
  • Save agwells/9a739b868e1f570587314b61714e10cf to your computer and use it in GitHub Desktop.
Save agwells/9a739b868e1f570587314b61714e10cf to your computer and use it in GitHub Desktop.
Ways to make a browser clear its cached HTTP basic auth credentials
<?php
function require_auth() {
$AUTH_USER = 'admin';
$AUTH_PASS = 'admin';
header('Cache-Control: no-cache, must-revalidate, max-age=0');
$has_supplied_credentials = !(empty($_SERVER['PHP_AUTH_USER']) && empty($_SERVER['PHP_AUTH_PW']));
$is_not_authenticated = (
!$has_supplied_credentials ||
$_SERVER['PHP_AUTH_USER'] != $AUTH_USER ||
$_SERVER['PHP_AUTH_PW'] != $AUTH_PASS
);
if ($is_not_authenticated) {
header('HTTP/1.1 401 Authorization Required');
header('WWW-Authenticate: Basic realm="Access denied"');
exit;
}
}
if (array_key_exists('logout', $_REQUEST)) {
header('HTTP/1.1 401 Authorization Required');
header('WWW-Authenticate: Basic realm="Access denied"');
exit();
}
require_auth();
?><p>You're in!</p>
<p><a href="?logout=401">Log out via 401</a></p>
<p><a href="//nosuchuser@<?php echo $_SERVER['HTTP_HOST']; echo $_SERVER['REQUEST_URI']; ?>">Log out via username in URL</a></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment