DaniWeb IT Discussion Community

Code Snippets (http://www.daniweb.com/code/)
-   php (http://www.daniweb.com/code/php.html)
-   -   PHP functions to handle .htpasswd file (http://www.daniweb.com/code/snippet798.html)

MitkOK php syntax
Dec 29th, 2007
I wrote four simple functions to manipulate .htpasswd file ( Apache ).

  1. <?php
  2. /*
  3.  
  4.  Author : Mitko Kostov
  5.  Weblog : http://mkostov.wordpress.com
  6.  Mail :mitko.kostov@gmail.com
  7.  Date : 12/21/2007
  8.  Used : PHP and Smarty
  9.  
  10. */
  11. // function to register user
  12. function regUser() {
  13.  
  14.  
  15.  
  16.  
  17. $filename = 'members/password/.htpasswd';
  18. $data = $_POST['username'].":".htpasswd($_POST['password'])."\n";
  19. if (is_writable($filename)) {
  20.  
  21.  
  22. if (!$handle = fopen($filename, 'a')) {
  23. echo "Cannot open file ($filename)";
  24. exit;
  25. }
  26.  
  27.  
  28. if (fwrite($handle, $data) === FALSE) {
  29. echo "Cannot write to file ($filename)";
  30. exit;
  31. }
  32.  
  33. // echo "Success, wrote ($data) to file ($filename)";
  34.  
  35. fclose($handle);
  36.  
  37. } else {
  38.  
  39. echo "The file $filename is not writable";
  40. }
  41.  
  42. }
  43.  
  44. // function to show all users and passwords ( encrypted )
  45. function showUser()
  46. {
  47.  
  48.  
  49. $file = file('members/password/.htpasswd');
  50. $array = array();
  51. $count = count($file);
  52. for ($i = 0; $i < $count; $i++)
  53. {
  54. list($username, $password) = explode(':', $file[$i]);
  55. $array[] = array("username" => $username, "password" => $password);
  56. }
  57.  
  58. return $array;
  59. }
  60. function delUser($username) {
  61.  
  62. $fileName = file('members/password/.htpasswd');
  63. $pattern = "/". $username."/";
  64.  
  65. foreach ($fileName as $key => $value) {
  66.  
  67. if(preg_match($pattern, $value)) { $line = $key; }
  68. }
  69.  
  70.  
  71. unset($fileName[$line]);
  72.  
  73. if (!$fp = fopen('members/password/.htpasswd', 'w+'))
  74. {
  75.  
  76. print "Cannot open file ($fileName)";
  77.  
  78. exit;
  79. }
  80.  
  81.  
  82. if($fp)
  83. {
  84.  
  85. foreach($fileName as $line) { fwrite($fp,$line); }
  86.  
  87. fclose($fp);
  88. }
  89.  
  90. }
  91.  
  92.  
  93. // function for encrypting password
  94. function htpasswd($pass)
  95.  
  96. {
  97.  
  98. $pass = crypt(trim($pass),base64_encode(CRYPT_STD_DES));
  99.  
  100. return $pass;
  101.  
  102. }
  103.  
  104. ?>