Home >> Snippet List >> Snippet

Name
Use htpasswd file with PHPscripts
Description
This is a way to use an existing htpasswd file with your PHP-based authentication scripts by using a combination of the substr() and the crypt() function to match the value entered by the user for $PHP_AUTH_PW, and an entry in the htpasswd file
PHP Snippet
< ?php
 
IF (!ISSET($PHP_AUTH_USER)) {
 
         HEADER('WWW-Authenticate: Basic realm="Private"');
         HEADER('HTTP/1.0 401 Unauthorized');
         ECHO 'Authorization Required.';
         EXIT;
 
} ELSEIF (ISSET($PHP_AUTH_USER)) {
 
         $filename = "/path/to/.htpasswd";
         $fp = FOPEN($filename, "r");
         $file_contents = FREAD($fp, FILESIZE($filename));
         FCLOSE($fp);
 
         // Place each line in user info file into an array
 
         $Line = EXPLODE("n", $file_contents);
 
         // For as long as $i is less than the size of the $line array,
         // explode each array element into a username and password
         // pair and attempt to match to $PHP_AUTH_USER and
         // $PHP_AUTH_PW values
 
         $i = 0;
 
         WHILE($i <= SIZEOF($Line)) {
                 $data_pair = EXPLODE(":", $Line[$i]);
 
                 IF ($data_pair[0] == "$PHP_AUTH_USER") {
 
                 // get salt from $data_pair[1]
                 $salt = SUBSTR($data_pair[1], 0, 2);
 
                 // encrypt $PHP_AUTH_PW based on $salt
                 $enc_pw = CRYPT($PHP_AUTH_PW, $salt);
 
                 // try to match encrypted passwords
                         IF ($data_pair[1] == "$enc_pw") {
 
                                 $auth = 1;
                                 BREAK;
 
                         } ELSE {
 
                                 $auth = 0;
 
                         }
 
                 } ELSE {
 
                         $auth = 0;
 
                 }
 
                 $i++;
 
         }
 
 
         // check value of $auth
 
         IF ($auth == "1") {
 
                 ECHO "You're authorized.";
 
         } ELSE {
 
                 HEADER('WWW-Authenticate: Basic realm="Private"');
                 HEADER('HTTP/1.0 401 Unauthorized');
                 ECHO 'Authorization Required.';
                 EXIT;
 
         }
 
}
 
?>