Simple Authentication Page in PHP

As part of WINCACHE statistics page, I came across the need for making the WINCACHE.php file having some kind of authentication. Yes we will have an official WINCACHE statistics page shipping with the Release Candidate due sometime this month. To know more about this upcoming release please read this blog from the Developer on the team. This is the time that I learnt that PHP has built in authentication support. I am going to talk about basic authentication page using PHP. I will be using code snippet from our new WINCACHE.php page to explain how easily this can be achieved.

This functionality is available when PHP is running as an Apache module and not the CGI. So it also works with IIS configured to run PHP using FastCGI. This is how it works:

  • Use the header() function of PHP to send 'Authentication required' message to the browser.
  • Browser will pop up a window asking for USERNAME/PASSWORD.
  • Once the user fills in the USERNAME and PASSWORD the script containing the authentication code is called again.
  • But this three server variables are set. They are PHP_AUTH_USER, PHP_AUTH_PW and AUTH_TYPE.
  • So this time your script can do the actual authentication using these server variables.
  • PHP isset() function comes here handy as you can dictate when to call authentication windows and when to do the actual authentication.

Now let's work on actual code. The code we will work on is very simple. It will simply put a greeting message to users once they are authentication. And here goes the actual code.

<?php
define('USE_AUTHENTICATION', 1);
define('USERNAME', 'wincache');
define('PASSWORD', 'wincache');

if ( USE_AUTHENTICATION == 1 ) {
    if ( !isset($_SERVER['PHP_AUTH_USER'] ) || !isset( $_SERVER['PHP_AUTH_PW'] ) ||    
    $_SERVER['PHP_AUTH_USER'] != USERNAME || $_SERVER['PHP_AUTH_PW'] != PASSWORD ) {
        header( 'WWW-Authenticate: Basic realm="WINCACHE Log In!"' );
        header( 'HTTP/1.0 401 Unauthorized' );
        exit;
    }
    else
    {
        echo "Welcome WINCACHE User.";
    }
}
?>

One important note, in order to have this work in php.ini file directive cgi.rfc2616_headers should be set to 0.

That's it and you are done. Hopefully this post will help you writing basic authentication page in PHP. Thanks for patient reading and good bye. PHP also supports digest authentication but that's another blog post.

Don.

Edit: The above works only if your site is configured in IIS to use 'Anonymous authentication'. For a generic PHP authentication solution which will work well on IIS look here.

No Comments