How to Simple HTTP Authentication using PHP

That’s all it takes to have the little box show up and demand a username and password. Now all you have to do is check the submitted username and password against the correct ones. Simply check the $_SERVER[‘PHP_AUTH_USER’] and $_SERVER[‘PHP_AUTH_PW’] global variables.

HTML and PHP Code

$authenticate = false;
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
    $name = $_SERVER['PHP_AUTH_USER'];
    $pass = $_SERVER['PHP_AUTH_PW'];
    if ($name == 'user' && $pass == 'pass') {
        $authenticate = true;

if ($authenticate == false) {
    header('WWW-Authenticate: Basic realm="Restricted Page Enter Details To Continue"');
    header('HTTP/1.0 401 Unauthorized');
    echo "Authentication Failed Refresh To Do It Again";
} else {
            <h1>How to Simple HTTP Authentication using PHP</h1>
            <p>All Your Content Comes Here</p>

Leave a Reply

Your email address will not be published. Required fields are marked *