Skip to content

Instantly share code, notes, and snippets.

@gabrysiak
Created August 14, 2014 19:42
Show Gist options
  • Save gabrysiak/2a5fee6fc9e0234ec2be to your computer and use it in GitHub Desktop.
Save gabrysiak/2a5fee6fc9e0234ec2be to your computer and use it in GitHub Desktop.
PHP - Basic Auth
$password = null;
// mod_php
if (isset($_SERVER['PHP_AUTH_USER'])) {
$username = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
// most other servers
} elseif (isset($_SERVER['HTTP_AUTHENTICATION'])) {
if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']),'basic')===0)
list($username,$password) = explode(':',base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6)));
}
if (is_null($username)) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
die();
} else {
echo "<p>Hello {$username}.</p>";
echo "<p>You entered {$password} as your password.</p>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment