Created
May 5, 2014 14:35
-
-
Save HomenSimpsor/e27acb752cfdd67c5589 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Function change password in htpasswd. | |
Arguments: | |
$user > User name we want to change password to. | |
$newpass > New password | |
$type > Type of cryptogrphy: DES, SHA, MD5. | |
$salt > Option: Add your custom salt (hashing string). | |
Salt is applied to DES and MD5 and must be in range 0-9A-Za-z | |
$oldpass > Option: Add more security, user must known old password to change it. | |
This option is not supported for DES and MD5 without salt!!! | |
$path > Path to .htaccess file which contain the password protection. | |
Path to password file is obtained from this .htaccess file. | |
*/ | |
function changePass($user,$newpass,$type="SHA",$salt="",$oldpass="",$path=".htaccess") { | |
switch ($type) { | |
case "DES" : | |
$salt = substr($salt,0,2); //Salt must be 2 char range 0-9A-Za-z | |
$newpass = crypt($newpass,$salt); | |
if ($oldpass != null) $oldpass = crypt($oldpass,$salt); | |
break; | |
case "SHA" : | |
$newpass = '{SHA}'.base64_encode(sha1($newpass, TRUE)); | |
if ($oldpass != null) $oldpass = '{SHA}'.base64_encode(sha1($oldpass, TRUE)); | |
break; | |
case "MD5" : | |
$salt = substr($salt,0,8); //Salt must be max 8 char range 0-9A-Za-z | |
$newpass = crypt_apr1_md5($newpass, $salt); | |
if ($oldpass != null) $oldpass = crypt_apr1_md5($oldpass, $salt); | |
break; | |
default : | |
return false; | |
break; | |
} | |
$hta_arr = explode("\n", file_get_contents($path)); | |
foreach($hta_arr as $line) { | |
$line = preg_replace('/\s+/','',$line); // remove spaces | |
if ($line) { | |
$line_arr = explode('"', $line); | |
if (strcmp($line_arr[0],"AuthUserFile") == 0) { | |
$path_htaccess = $line_arr[1]; | |
} | |
} | |
} | |
$htp_arr = explode("\n", file_get_contents($path_htaccess)); | |
$new_file = ""; | |
foreach($htp_arr as $line) { | |
$line = preg_replace('/\s+/','',$line); // remove spaces | |
if ($line) { | |
list($usr, $pass) = explode(":", $line, 2); | |
if (strcmp($user,$usr) == 0) { | |
if ($oldpass != null) { | |
if ($oldpass == $pass) { | |
$new_file .= $user.':'.$newpass."\n"; | |
} else { | |
return false; | |
} | |
} else { | |
$new_file .= $user.':'.$newpass."\n"; | |
} | |
} else { | |
$new_file .= $user.':'.$pass."\n"; | |
} | |
} | |
} | |
$f=fopen($path_htaccess,"w") or die("couldn't open the file"); | |
fwrite($f,$new_file); | |
fclose($f); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment