I am trying to use the below code to automatically update a .htpasswd file. The file is updated but when I try to login using the USERNAME / PASSWORD I have added the file it does not work. I must have a problem using the crypt() function???? Or should I be doing something completely different???

$salt = "FB";
$user = $_POST['username'];
$pass = crypt($_POST['password'], $salt); // I have tried this using a salt like this.
// I have also tried it without a salt.

$filename = '.htpasswd';

$somecontent = $user.":".$pass."\r\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";

// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";

echo "Success, wrote ($somecontent) to file ($filename)";


} else {
echo "The file $filename is not writable";


Your help is most appreciated :-)