PHP HTTP Authentication

Tuesday, February 17, 2009

HTTP authentication is the same method used by server-controlled access. The HTTP protocol specifies a method for requesting access information through WWW-Authenticate header request. When browser receives WWW-Authenticate header, it will display a dialog box requesting username andd password. PHP provides some global variables in the $_SERVER superglobal array as follows:

  • PHP_AUTH_USER contains the value of username field
  • PHP_AUTH_PW contains the value of password field
  • PHP_AUTH_TYPE either Basic or Digest, contains the type of authorization being used
Here's an example of a PHP script that presents HTTP username/password dialog box and then validates the given values.
<?php
if (!isset($_SERVER['PHP_AUTH_USER']) ||
        $_SERVER['PHP_AUTH_USER'] != 'username' ||
        $_SERVER['PHP_AUTH_PW'] != 'password' ) {
    //on failed
    header('WWW-Authenticate: Basic realm="For Your Eyes Only"');
    header('HTTP/1.0 401 Unauthorized');
    echo '<h1>401 Unauthorized!</h1><strong>Forbidden</strong>';
    exit;
}

//on success
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Authentication Test</title>
</head>
<body>
<h2>Hello <?= $_SERVER['PHP_AUTH_USER'] ?>:</h2>
<p>You entered <?= $_SERVER['PHP_AUTH_PW'] ?> as your password!</p>
</body></html>


Hope it helps.

0 comments: