HTTP authentication with PHP

In my last article I showed you how to Password Protect with htaccess and htpasswd, and how to use PHP to add to your htpasswd file. In this article, I’ll show you how to use HTTP authentication, just like using htaccess, but this time you’ll be able to verify the login against a database.

So why would you want to do it this way? Well using htpasswd files to store logins can be quick and easy for a small number of logins, but if you get over 100 then things will begin to slow down. The way apache checks the file is by starting from the beginning, and checking against each line. So that means if the username and password they entered was invalid, it would go through ALL 100 lines. AND on top of that, it checks every time they access a page.

The Code

<?php
  if (!isset($_SERVER['PHP_AUTH_USER'])) {
   header('WWW-Authenticate: Basic realm="My Realm"');
   header('HTTP/1.0 401 Unauthorized');
   echo 'Text to send if user hits Cancel button';
   exit;
  } else {
   echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
   echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
  }
?>

The Explaination
Lines 2-6: This simply sends out the headers to make that login prompt appear if they aren’t logged in.

Lines 8-9: This outputs the login they used. Note that in a real site you would check the login against a database of some sort.

Quick Tip
Once the user has been verified, you could set some kind of session up and then check the session information each page view instead of re-checking the database every time.