note 31384 added to function.crypt
| From: | Martin at rack1 dot php dot net | Date: | Sat, 19 Apr 2003 21:41:53 +0000 |
| Subject: | note 31384 added to function.crypt | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-46822@lists.php.net to get a copy of this message | ||
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);
--
http://www.php.net/manual/en/function.crypt.php
http://master.php.net/manage/user-notes.php?action=edit+31384
http://master.php.net/manage/user-notes.php?action=delete+31384
http://master.php.net/manage/user-notes.php?action=reject+31384