nlopess Sun Nov 6 06:57:48 2005 EDT
Modified files:
/phpdoc/en/features http-auth.xml
Log:
improve the http auth script by making a smarter parsing function.
I hope this makes the page smaller
http://cvs.php.net/diff.php/phpdoc/en/features/http-auth.xml?r1=1.43&r2=1.44&ty=u
Index: phpdoc/en/features/http-auth.xml
diff -u phpdoc/en/features/http-auth.xml:1.43
phpdoc/en/features/http-auth.xml:1.44
--- phpdoc/en/features/http-auth.xml:1.43 Sat Aug 27 19:48:12 2005
+++ phpdoc/en/features/http-auth.xml Sun Nov 6 06:57:46 2005
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="iso-8859-1"?>
-<!-- $Revision: 1.43 $ -->
+<!-- $Revision: 1.44 $ -->
<chapter id="features.http-auth">
<title>HTTP authentication with PHP</title>
@@ -73,7 +73,7 @@
$users = array('admin' => 'mypass', 'guest' => 'guest');
-if (!isset($_SERVER['PHP_AUTH_DIGEST'])) {
+if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'" qop="auth" nonce="'.uniqid().'" opaque="'.md5($realm).'"');
@@ -81,24 +81,41 @@
die('Text to send if user hits Cancel button');
}
-// analyze the PHP_AUTH_DIGEST variable
-preg_match('/username="(?P<username>.*)",\s*realm="(?P<realm>.*)",\s*nonce="(?P<nonce>.*)",\s*uri="(?P<uri>.*)",\s*response="(?P<response>.*)",\s*opaque="(?P<opaque>.*)",\s*qop=(?P<qop>.*),\s*nc=(?P<nc>.*),\s*cnonce="(?P<cnonce>.*)"/',
$_SERVER['PHP_AUTH_DIGEST'], $digest);
-if (!isset($users[$digest['username']]))
- die('Username not valid!');
+// analyze the PHP_AUTH_DIGEST variable
+if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
+ !isset($users[$data['username']]))
+ die('Wrong Credentials!');
// generate the valid response
-$A1 = md5($digest['username'] . ':' . $realm . ':' .
$users[$digest['username']]);
-$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$digest['uri']);
-$valid_response =
md5($A1.':'.$digest['nonce'].':'.$digest['nc'].':'.$digest['cnonce'].':'.$digest['qop'].':'.$A2);
+$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
+$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
+$valid_response =
md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
-if ($digest['response'] != $valid_response)
+if ($data['response'] != $valid_response)
die('Wrong Credentials!');
// ok, valid username & password
-echo 'Your are logged in as: ' . $digest['username'];
+echo 'Your are logged in as: ' . $data['username'];
+
+// function to parse the http auth header
+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();
+
+ preg_match_all('@(\w+)=([\'"]?)([a-zA-Z0-9=./\_-]+)\2@', $txt, $matches,
PREG_SET_ORDER);
+
+ foreach ($matches as $m) {
+ $data[$m[1]] = $m[3];
+ unset($needed_parts[$m[1]]);
+ }
+
+ return $needed_parts ? false : $data;
+}
?>
]]>
</programlisting>