Projects Personal Contact Rss

HTTP Authentication in PHP

When combining sessions with HTTP Auth in order to maintain state. The difficulty surrounding HTTP Auth is that even after you "logout", the browser will continue to send the correct username and password with each request. Thus immediately logging you back in again - unless you use the states to keep track carefully.

In this example we will use two session variables to maintain state and we tell the page that we want to login our logout via an argument in the query string, e.g. ?login ?logout

The two state variables are:

  • LOGGEDIN - Very simple state - either you are logged in or not
  • LOGGEDOUT - Will be TRUE if we have logged out. It's primary purpose is to scupper the browser provided password and prevent the authentication routines from running. It gets reset to FALSE when we want to login

Additional benefits to this method are that we only need to authenticate upon login once. Normal code implemented HTTP Auth routines authenticate with every page request

Source code: Example page protected with PHP HTTP Auth

Source code: PHP HTTP Auth include file

In order to use this to protect any page you need to copy the file to your server and then simply include or require it in any page.
You may wish to set the variable $HTTP_AUTH_REALM to a string before including this as this will change the Basic Realm information in the auth dialog box to a string of your choice.

You should also look at the checkpw() function and replace that with something that will check your user credentials correctly. Input is username, password and it should return TRUE or FALSE if the credentials supplied are OK or not.

Finally, on any page to effect a change of state from logged in to logged out or vice-versa, you simply have to make a link to a page with "login" or "logout" in the url's Query String (that is the bit after the ?), e.g. page.php?login

A working example is shown below, the default username is "paul" and password is "gregg"

I hope this code serves as useful learning material. Good luck.

Welcome to this page.

You are not logged in.
Log in

Debug: Test username/password is: paul/gregg
array(2) {

All content © Paul Gregg, 1994 - 2024
Page last updated: 15 November 2023 17:34:16.
This site has been online since 5th October 2000
Previous websites live at various URLs since 1994