note 45960 deleted from features.http-auth by danbrown

From: Date: Mon, 20 Jun 2011 15:24:20 +0000
Subject: note 45960 deleted from features.http-auth by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-180755@lists.php.net to get a copy of this message
Note Submitter: bernard dot paques at bigfoot dot com ---- The approach described in the manual works only at servers where PHP is ran as an Apache module. Where PHP is ran as a CGI module, credentials are always empty, whether the user actually fills the authentication box or not. Apparently the set of Apache variables exposed to PHP is restricted when PHP runs in CGI mode, and this explains why $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] are not set. The solution is to select one Apache variable actually transmitted to PHP even in CGI mode, and to put in it authentication data submitted by the browser. Look at the following directive added to the .htaccess file: <IfModule mod_rewrite.c> RewriteEngine on RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L] </IfModule> This directive states that, if mod_rewrite is available, credentials gathered from the HTTP header Authorization are put into the $_SERVER['REMOTE_USER'] variable. To build up on RFC 2617 on HTTP Authentication, if the surfer wishes to send the userid "Aladdin" and password "open sesame", the browser will add the following header attribute to the HTTP request: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== Thanks to the rewrite directive put in .htaccess, the triggered PHP script will catch credentials through $_SERVER['REMOTE_USER'] as follows: $_SERVER['REMOTE_USER'] = Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== From there all you have to do is to decode base64 credentials, and to split the string to retrieve user name and password, as described into the RFC 2617. Before you use $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'], check if these variables are empty. If yes, attempt to rebuild them by using $_SERVER['REMOTE_USER']. The following snippet does exactly that: <?php // maybe we have caught authentication data in $_SERVER['REMOTE_USER'] if((!$_SERVER['PHP_AUTH_USER'] || !$_SERVER['PHP_AUTH_USER']) && preg_match('/Basics+(.*)$/i', $_SERVER['REMOTE_USER'], $matches)) { list($name, $password) = explode(':', base64_decode($matches[1])); $_SERVER['PHP_AUTH_USER'] = strip_tags($name); $_SERVER['PHP_AUTH_PW'] = strip_tags($password); } ?> The full script used to build a secured RSS feed is available here: http://www.yetanothercommunitysystem.com/yacs/scripts/ Of course, this trick works only if the mod_rewrite module is available, and if you have changed the .htaccess file as explained above.

« previous php.notes (#180755) next »