Skip to content

Instantly share code, notes, and snippets.

@noncent
Last active September 13, 2021 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noncent/ae0e4cfa6fc46d0535099d4705f1f575 to your computer and use it in GitHub Desktop.
Save noncent/ae0e4cfa6fc46d0535099d4705f1f575 to your computer and use it in GitHub Desktop.
PHP web auth sample code. Add Web Authentication in PHP. Web Authentication PHP. PHP HTTP Basic Auth. HTTP Basic Auth. Basic Auth
<?php
header('Cache-Control: no-cache, must-revalidate, max-age=0');
function html($message)
{
return <<<HTML
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>$message</title><style type="text/css">h1.error{left:0;line-height:200px;margin-top:-100px;position:absolute;text-align:center;top:50%;width:100%;font-size:15em;color:#dadada;-webkit-text-fill-color:#dadada;-webkit-text-stroke-width:1px;-webkit-text-stroke-color:black}</style></head><body><h1 class="error">$message</h1></body></html>
HTML;
}
$AUTH_USER = 'admin';
$AUTH_PASS = 'admin';
// First check if a username was provided.
if (!isset($_SERVER['PHP_AUTH_USER']) || empty($_SERVER['PHP_AUTH_USER']) || ($_SERVER['PHP_AUTH_USER'] !== $AUTH_USER) || ($_SERVER['PHP_AUTH_PW'] !== $AUTH_PASS)) {
// If no username provided, present the auth challenge.
header('WWW-Authenticate: Basic realm="My Website"');
header('HTTP/1.0 401 Unauthorized');
// User will be presented with the username/password prompt
// If they hit cancel, they will see this access denied message.
echo html('403');
exit; // Be safe and ensure no other content is returned.
}
// If we get here, username was provided. Check password.
if ($_SERVER['PHP_AUTH_PW'] == $AUTH_PASS) {
// here is the gold if you are validated
// my tons of code here
echo html('Success');
} else {
echo $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment