Reseting htpasswd with PHP

15 Jan 2010

by hemanth

<?php

function load_htpasswd($file)
{
    if(
file_exists($file) && filesize($file) > 0)
    {
        
$htpasswd file($file);
        
$auth = array();
        foreach(
$htpasswd as $h)
        {
            
$array explode(':',$h);
            
$user $array[0];
            
$pass chop($array[1]);
            
$auth[$user] = $pass;
        }
        return 
$auth;
    }
    else
        return array();
}

function 
sha1_htpasswd($pass)
{
    return 
'{SHA}' base64_encode(pack('H*'sha1($pass)));
}

function 
valid_user($userpass$user$pass){

    if(!isset(
$userpass[$user])){
        echo 
"User Password is not set. Please contact ADMIN to get default password<br/>";
        return 
false;
    }

    
$test $userpass[$user];
    if(
strcmp(substr($test,0,5),'{SHA}') == 0)
        
$status strcmp(sha1_htpasswd($pass),$test);
    else
        
$status strcmp(crypt($passsubstr($test,0,CRYPT_SALT_LENGTH)),$test);

    if(
$status != 0){
        echo 
"User Password is incorrect!<br/>";
        return 
false;
    }

    return 
true;
}

// ====================
// MAIN ACTION BLOCK
// ====================

$app $_POST['app'];

$file 'auths/' $app '-auth-file';

$userpass load_htpasswd($file);

if(
valid_user($userpass,$_POST['userName'],$_POST['userPwd'])){

    
$login $_POST['userName'];
    
$newPwd $_POST['newpwd'];
    
$rnewPwd$_POST['rnewpwd'];

    if (
"$newPwd" === "$rnewPwd"){
        
$cmd '/usr/bin/htpasswd -sb ' $file ' ' $login ' ' $newPwd ' 2>&1';
        
// echo "Executing $cmd ...<br/>";
        
$out shell_exec($cmd);
        echo 
"$out";
        echo 
"Your password has been changed!<br/>";
    }
    else{
        echo 
"Password doesn't match<br/>";
        exit();
    }
}
?>

# the inputs are passed to the php scripts from a simple HTML form
?>
Share this