Zend - The PHP Company




Authentication

Add Code


Protecting whole directories with MySQL  

Type: code fragment
Added by: kliver
Entered: 16/07/2004
Last modified: 07/12/2003
Rating: - (fewer than 3 votes)
Views: 5022
Problem: PHP authentication doesn't protect whole directories, HTTP authentication isn't automated (you always have those inflexible txt files) Solution: Using this script lets you update your .htpasswd file taking usernames and passwords from a MySQL source Just execute this script everytime a password/username combination is newly entered or changed. It's maybe not the "perfect" way, but the only way I found to protect whole directories with MySQL data.


<?
/***************************************
** Title.........: Updating .htpasswd with MySQL
** Version.......: 1.0
** Author........: Oliver Kuster
** Last changed..: July, 16th 2004
** Application...: Call this script whenever a
**                 username/password entry is 
**                 made or changed.
***************************************/ 


/***************************************
** Open the .htpasswd file, reading mood
** Close it
** Open it again, ready to overwrite
***************************************/ 

    
$fp=fopen("../../members/.htpasswd","r") or die ("Can't open file");

    
fclose($fp);

    
$fp=fopen("../../members/.htpasswd","w");

/***************************************
** Get the data out of mysql (don't forget
** to connect to your MySQL database!
***************************************/ 

$result_list mysql_query("SELECT id,username,password FROM users");
while (list(
$ht_id,$ht_username,$ht_password) = mysql_fetch_row$result_list )) { 

    
/***************************************
    ** Encrypt passwords for .htpasswd use
    ** Servers might use a "salt" - check
    ** manual on how to implement a salt
    ** and check with your ISP what salt
    ** they use.
    ** Write every entry from MySQL into
    ** the .htpasswd file in the classical
    ** username:password way.
    ***************************************/ 
    
    
$password_enc crypt ($ht_password);

    
$content "$ht_username:$password_encn";
    
    
fwrite($fp,$content);

}

fclose($fp);

?>


Usage Example




Rate This Script





Search



This Category All Categories