reenadak

class for .htaccess user management

Sep 25th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.02 KB | None | 0 0
  1. <?php
  2.  
  3. // Usage
  4. // $htpasswd = new htpasswd('.htpasswd');
  5. // path to your .htpasswd file
  6.  
  7. // Usage Example
  8.   //  if($htpasswd->user_update($user,$password))
  9.  //   {
  10.   //    echo "Password updated successfully for '".$user."'\n";
  11.   //  }
  12.  //   else
  13.  //   {
  14.  //     echo "Password updated failed for '".$user."'\n";
  15.  //   }
  16.  
  17. // Save as .htpasswd.php
  18. class htpasswd {
  19.     var $fp;
  20.     var $filename;
  21.  
  22.     function htpasswd($filename) {
  23.         @$this->fp = fopen($filename,'r+') or die('Invalid file name');
  24.         $this->filename = $filename;
  25.     }
  26.  
  27.     function user_exists($username) {
  28.         rewind($this->fp);
  29.             while(!feof($this->fp) && trim($lusername = array_shift(explode(":",$line = rtrim(fgets($this->fp)))))) {
  30.                 if($lusername == $username)
  31.                     return 1;
  32.             }
  33.         return 0;
  34.     }
  35.  
  36.     function user_add($username,$password) {
  37.         if($this->user_exists($username))
  38.             return false;
  39.         fseek($this->fp,0,SEEK_END);
  40.         fwrite($this->fp,$username.':'.crypt($password,substr(str_replace('+','.',base64_encode(pack('N4', mt_rand(),mt_rand(),mt_rand(),mt_rand()))),0,22))."\n");
  41.         return true;
  42.     }
  43.  
  44.     function user_delete($username) {
  45.         $data = '';
  46.         rewind($this->fp);
  47.         while(!feof($this->fp) && trim($lusername = array_shift(explode(":",$line = rtrim(fgets($this->fp)))))) {
  48.             if(!trim($line))
  49.                 break;
  50.             if($lusername != $username)
  51.             $data .= $line."\n";
  52.         }
  53.         $this->fp = fopen($this->filename,'w');
  54.         fwrite($this->fp,rtrim($data).(trim($data) ? "\n" : ''));
  55.         fclose($this->fp);
  56.         $this->fp = fopen($this->filename,'r+');
  57.         return true;
  58.     }
  59.  
  60.     function user_update($username,$password) {
  61.         rewind($this->fp);
  62.             while(!feof($this->fp) && trim($lusername = array_shift(explode(":",$line = rtrim(fgets($this->fp)))))) {
  63.                 if($lusername == $username) {
  64.                     fseek($this->fp,(-15 - strlen($username)),SEEK_CUR);
  65.                     fwrite($this->fp,$username.':'.crypt($password,substr(str_replace('+','.',base64_encode(pack('N4', mt_rand(),mt_rand(),mt_rand(),mt_rand()))),0,22))."\n");
  66.                     return true;
  67.                 }
  68.             }
  69.         return false;
  70.     }
  71. }
  72.  
  73. ?>
Add Comment
Please, Sign In to add comment