Basic HTTP Authentication with PHP

Basic HTTP Authentication is easily accomplished at the web server level (by
way of .htaccess with Apache or inside your nginx configuration file) but
did you know you could pull it off inside of a PHP script? You bet your butt
you can!

First, you will need to interrogate the _SERVER variables that contain the
username and password. If they are set (and are the correct credentials) you
can proceed with loading the rest of the page. Otherwise, present the user with
the authentication headers with the header function:

if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])
    && $_SERVER['PHP_AUTH_USER'] === 'admin'
    && $_SERVER['PHP_AUTH_PW'] === 'password') {

    // User is properly authenticated...

} else {
    header('WWW-Authenticate: Basic realm="Secure Site"'
    header('HTTP/1.0 401 Unauthorized'
    exit('This site requires authentication'
}

Keep in mind that this is just an example and I do not recommend storing
plaintext credentials in your script. At worst, you could store the hash for
the password and check that against the hash generated from the supplied
_SERVER['PHP_AUTH_PW']. At best, you could be loading those credentials from
a datastore so that you don’t have any usernames, passwords or hashes in your
script. Going that route would also let you easily maintain multiple user
accounts instead of just one.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.