PHP 7.2.0 Beta 1 Released

Voting

Please answer this simple SPAM challenge: five plus three?
(Example: nine)

The Note You're Voting On

ken_php_net at wolfpackinteractive dot com
13 years ago
Say you have password and groups files in standard Apache format (htpasswd etc.), but you want to apply authorization based on something other than filename, ie something you can't catch in .htaccess.  You want to emulate the server behavior in PHP -- the equivalent of:

AuthType Basic
AuthName "Members"
AuthUserFile /path/to/.htpasswd
AuthGroupFile /path/to/.groups
require group Members

Here's what I came up with:

<?PHP

$AuthUserFile
= file("/path/to/.htpasswd");
$AuthGroupFile = file("/path/to/.groups");
$group = "Members";
$realm = "Members";

function
authenticate(){
   
header("WWW-Authenticate: Basic realm=\"$realm\"");
   
header('HTTP/1.0 401 Unauthorized');
    echo
"You must enter a valid user name and password to access the requested resource.";
    exit;
}

for(;
1; authenticate()){
    if (!isset(
$HTTP_SERVER_VARS['PHP_AUTH_USER']))
        continue;

   
$user = $HTTP_SERVER_VARS['PHP_AUTH_USER'];
    if(!
preg_grep("/$group: $user$/", $AuthGroupFile))  # (format assumptions)
       
continue;

    if(!(
$authUserLine = array_shift(preg_grep("/$user:.*$/", $AuthUserFile))))
        continue;

   
preg_match("/$user:((..).*)$/", $authUserLine, $matches);
   
$authPW = $matches[1];
   
$salt = $matches[2];
   
$submittedPW = crypt($HTTP_SERVER_VARS['PHP_AUTH_PW'], $salt);
    if(
$submittedPW != $authPW)
        continue;

    break;
}

echo
"You got in!"
?>

<< Back to user notes page

To Top