← ServerPilot Docs

How to Perform HTTP Digest Authentication with PHP

HTTP Digest Authentication data sent to your app through request headers is accessible through the $_ENV['HTTP_AUTHORIZATION'] variable in PHP.

You can parse the $_ENV['HTTP_AUTHORIZATION'] variable within your PHP scripts to get the submitted Auth Digest values.

For example, the following script:

<?php
$digest_values = http_digest_parse($_ENV['HTTP_AUTHORIZATION']);

var_dump($digest_values);

// Function to parse the http auth header.
// From http://www.php.net/manual/en/features.http-auth.php
function http_digest_parse($txt)
{
    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}
?>

will output:

array(7) {
  ["username"]=>
  string(3) "foo"
  ["nonce"]=>
  string(34) "dcd98b7102dd2f0e8b11d0f600bfb0c093"
  ["uri"]=>
  string(11) "/digest.php"
  ["qop"]=>
  string(4) "auth"
  ["nc"]=>
  string(8) "00000001"
  ["cnonce"]=>
  string(8) "0a4f113b"
  ["response"]=>
  string(32) "6629fae49393a05397450978507c4ef1"
}

For a complete example of performing digest authorization in PHP, see www.php.net/manual/en/features.http-auth.php.

Launch your first site in 5 minutes