note 31384 deleted from function.crypt by aidan
| From: | aidan@php.net | Date: | Mon, 05 Jul 2004 10:28:35 +0000 |
| Subject: | note 31384 deleted from function.crypt by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72590@lists.php.net to get a copy of this message | ||
Note Submitter: Martin F.
----
To modify an existing .htpasswd or to create a new one:
-------------------------------------------------------
$file = '.htpasswd';
// Read the file into the array $passwords
// This part is not necessary if you don't have an existing .htpasswd and want to create a new
one.
$lines = file($file);
foreach($lines as $nokey => $line)
{
$array = explode(':',$line);
$user = $array[0];
$password = chop($array[1]);
$passwords[$user] = $password;
}
// Now you have the array $passwords with the users as keys and the (encrypted) passwords as values.
// Add a user
$newuser = 'foo';
$newpass = 'bar';
// Next part to generate a random salt with letters and/or numbers
mt_srand((double)microtime()*1000000);
$chars =
array_merge(range('a','z'),range('A','Z'),range(0,9));
for($i=0;$i<2;$i++)
{
$salt .= $chars[mt_rand(0,count($chars)-1)];
}
// Salt $salt created
// Now add the user
$passwords[$newuser] = crypt($newpass,$salt);
// Now the array $passwords contains the existing users and (encrypted) passwords from the file and
the new user (and the encrypted password).
// Delete a user
$deleteuser = 'foobar';
unset($passwords[$deleteuser]);
// Update the file
$filehandle = fopen($file,'w');
foreach($passwords as $user => $password)
{
fputs($filehandle, "$user:$password\n");
}
fclose($filehandle);