Automatically Generate and Store Htpassword in PHP

by MANIMUTHUPANDI 2014-06-04 20:06:49


Htpassword is a mechanism that is supported by apache.
Htpassword is useful to protect the dierectory, as we know.
I Have created a code for my website, to periodically update my htpassword and htusername.
Use my code given below  in a seperate file(called htpassword-generator.php) and add this file to a cron job in linux for a specific period , Say for one month.
You will get the mail of your htusername and password as modified.
Htusername is generated with random string.
Htpassword is genereated with crypt() function.Random string and random salt is used
Finally this username and password is written to the file .htpasswd
You can use this username and password from mail to login  your htpassword protected website.

//Coding goes here . . . .
<?
$uname=generateRandomString(15,"uname");
$password=generateRandomString(15,"pwd");
$salt=generateRandomString(2,"salt");
//You have to take this username and password to your mail
echo"userName= $uname
Password= $password
";
@mail("your email id","Htusername and Htpassword updated for your site","userName= $uname
Password= $password
",$additional_header);
//Define $additional_header yourself
$d=crypt($password,$salt);
$credentials="$uname:$d";
$filePointer= fopen(".htpasswd", 'w');
fwrite($filePointer, "$credentials");
fclose($filePointer);
function generateRandomString($length,$category)
{
    if($category=="pwd")
    $possible_charactors = "abcdefg&hijklmnopqrstuvwxyz!@#$%^*()1234567890ABCDEFG=HIJKLMNOPQRSTUVWXYZ";
    else if($category=="uname")
    $possible_charactors = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    else if($category=="salt")
    $possible_charactors = "abcdefghijklmnopqrstuvwxyz";
    $string = "";$stringArray_present=array();
    while(strlen($string)<$length)
    {
    $random_num=rand(0,(strlen($possible_charactors)-1));
    $s1= $possible_charactors[$random_num];
    if(!in_array($s1,$stringArray_present))
    {$string .=$s1;array_push($stringArray_present,$s1);}
    }
    return($string);
}
?>
//Paste this code in .htaccess
AuthName "Manager"
AuthType Basic
AuthUserFile /opt/lampp/htdocs/.htpasswd
require valid-user
1155
like
0
dislike
0
mail
flag

You must LOGIN to add comments