Basic HTTP authentication is rudimentary method of requesting a username and password, then allowing or denying access based on the credentials entered. You’ve probably seen it in action somewhere or another. If you try to subscribe to a protected RSS feed, such as the feed for your friends timeline on Twitter, for example.
It’s not the most user-friendly way to authenticate a user, but it has it’s uses. It’s great for APIs and other things where a pretty interface isn’t being delivered, where a more low-level solution is required. It’s also good for restricting access to parts of your server that most people just don’t need to be accessing.
Now how do you do that for yourself? It’s a fairly simple matter with PHP. Basically you send an HTTP/1.0Â 401Â Unauthorized
header, and a WWW-Authenticate: Basic realm="Name of Realm"
. This tells the client that it’s not authorized to view the page, and that it should try to become authorized.
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.
Here’s an example of a minimal script to request and check a username and password:
<?php if ( !isset($_SERVER['PHP_AUTH_USER']) ) { header('WWW-Authenticate: Basic realm="You Shall Not Pass"'); header('HTTP/1.0 401 Unauthorized'); exit; } else { if ( $_SERVER['PHP_AUTH_USER'] == 'me' && $_SERVER['PHP_AUTH_PW'] == 'password' ) { echo "<p>Welcome, {$_SERVER['PHP_AUTH_USER']}.</p>"; } else { echo "Wrong password, Balrog!"; } } ?>
A quick word of caution: Whenever you store passwords, be they in a database, text file or simply hard-coded into the script, you should always encrypt them with a one-way hash. The PHP Security Consortium has an article on how to do this.