PHP functions to handle .htpasswd file

MitkOK 1 Tallied Votes 602 Views Share

I wrote four simple functions to manipulate .htpasswd file ( Apache ).

LastMitch commented: This is a neat code snippet. Thanks for sharing! +12
<?php
/*
 
 Author : Mitko Kostov
 Weblog : http://mkostov.wordpress.com 
 Mail :mitko.kostov@gmail.com
 Date : 12/21/2007
 Used : PHP and Smarty
     
*/
// function to register user
function regUser() {
       
      
       
     
        $filename = 'members/password/.htpasswd';
        $data = $_POST['username'].":".htpasswd($_POST['password'])."\n";
   if (is_writable($filename)) {

   
            if (!$handle = fopen($filename, 'a')) {
                echo "Cannot open file ($filename)";
                exit;
            }

   
            if (fwrite($handle, $data) === FALSE) {
                echo "Cannot write to file ($filename)";
                exit;
            }

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

         fclose($handle);

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

}

// function to show all users and passwords ( encrypted )
function showUser()
{

      
     $file = file('members/password/.htpasswd');
     $array = array();
     $count = count($file);
     for ($i = 0; $i < $count; $i++)
     {
                list($username, $password) = explode(':', $file[$i]);
                $array[] = array("username" => $username, "password" => $password);
      }

     return $array;
}
function delUser($username) {
 
   $fileName = file('members/password/.htpasswd');
   $pattern = "/". $username."/";
  
   foreach ($fileName as $key => $value) {
   
   if(preg_match($pattern, $value)) { $line = $key;  }
   }
 
 
  unset($fileName[$line]);
 
   if (!$fp = fopen('members/password/.htpasswd', 'w+'))
      {
  
        print "Cannot open file ($fileName)";
     
        exit;
      }
 
 
     if($fp)
      {
       
        foreach($fileName as $line) { fwrite($fp,$line); }
       
        fclose($fp);
      }
 
}
 

// function for encrypting password   
function htpasswd($pass)

{

     $pass = crypt(trim($pass),base64_encode(CRYPT_STD_DES));

     return $pass;

}

?>
Member Avatar for LastMitch
LastMitch

I wrote four simple functions to manipulate .htpasswd file ( Apache ).

Thanks for sharing. I actually like this code snippet and the file is called: htpasswd.php.

You should have included your other files from here

https://github.com/MrMEEE/dommerbord/tree/master/admin

Then it would be eaiser to grasp.

But I didn't know it til now but the code snippet does work:

1d051fa3663a0d4e2d1b3012db425ee0

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.