jump to navigation

Basic HTTP Authentication With PHP May 24, 2011

Posted by Tournas Dimitrios in PHP.

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.
These dialog boxes are certainly familiar to you :


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:


if ( !isset($_SERVER['PHP_AUTH_USER']) ) {
header('WWW-Authenticate: Basic realm="This page demands autherization , please fill your Credentials"');
header('HTTP/1.0 401 Unauthorized');
else {
if ( $_SERVER['PHP_AUTH_USER'] == 'user' && $_SERVER['PHP_AUTH_PW'] == 'password' ) {
echo "<p>Welcome, {$_SERVER['PHP_AUTH_USER']}.</p>";
} else {
echo "Wrong password, Tray again!";


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.



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s