PHP class used to parse. htpasswd files
. Htpasswd File example: User1: {SHA} kGPaD671VNU0OU5lqLiN/h6Q6ac = User2: {SHA} npMqPEX3kPQTo + x/+ ZckHDrIcQI = User3: {SHA} q1Fh2LTUjjkncp11m0M9WUH5Zrw =
- Class Htpasswd {
- Private $ file = '';
- Private $ salt = 'aynlj2h. 74VEfI ^ BZElc-Vb6G0ezE9a55-Wj ';
- Private function write ($ pairs = array ()){
- $ Str = '';
- Foreach ($ pairs as $ username => $ password ){
- $ Str. = "$ username: {SHA} $ password \ n ";
- }
- File_put_contents ($ this-> file, $ str );
- }
- Private function read (){
- $ Pairs = array ();
- $ Fh = fopen ($ this-> file, 'r ');
- While (! Feof ($ fh )){
- $ Pair_str = str_replace ("\ n", '', fgets ($ fh ));
- $ Pair_array = explode (': {SHA}', $ pair_str );
- If (count ($ pair_array) = 2 ){
- $ Pairs [$ pair_array [0] = $ pair_array [1];
- }
- }
- Return $ pairs;
- }
- Private function getHash ($ clear_password = ''){
- If (! Empty ($ clear_password )){
- Return base64_encode (sha1 ($ clear_password, true ));
- } Else {
- Return false;
- }
- }
- Public function _ construct ($ file ){
- If (file_exists ($ file )){
- $ This-> file = $ file;
- } Else {
- Die ($ file. "doesn't exist .");
- Return false;
- }
- }
- Public function addUser ($ username = '', $ clear_password = ''){
- If (! Empty ($ username )&&! Empty ($ clear_password )){
- $ All = $ this-> read ();
- If (! Array_key_exists ($ username, $ all )){
- $ All [$ username] = $ this-> getHash ($ clear_password );
- $ This-> write ($ all );
- }
- } Else {
- Return false;
- }
- }
- Public function deleteUser ($ username = ''){
- $ All = $ this-> read ();
- If (array_key_exists ($ username, $ all )){
- Unset ($ all [$ username]);
- $ This-> write ($ all );
- } Else {
- Return false;
- }
- }
- Public function doesUserExist ($ username = ''){
- $ All = $ this-> read ();
- If (array_key_exists ($ username, $ all )){
- Return true;
- } Else {
- Return false;
- }
- }
- Public function getClearPassword ($ username ){
- Return strtolower (substr (sha1 ($ username. $ this-> salt), 4, 12 ));
- }
- }
- $ PasswdHandler = new Htpasswd ('/home/myuser/. htpasswd ');
- // Add a user with name 'user1' and password 'I prefer to use passphrase rather than password.' if it doesn' t exist in. htpasswd.
- $ PasswdHandler-> addUser ('user1', 'I prefer to use passphrase rather than password .');
- // Delete the user 'user1' if it exists in. htpasswd.
- $ PasswdHandler-> deleteUser ('user1 ');
- // Check if user 'user1' exists in. htpasswd.
- If ($ passwdHandler-> doesUserExist ('user1 ')){
- // User 'user1' exists.
- }
|