---
title: "Reseting htpasswd with PHP"
description: "0) { $htpasswd = file($file); $auth = array(); foreach($htpasswd as $h) { $array = explode(’:’,$h); $user = $array[0]; $pass."
url: "https://h3manth.com/scribe/reseting-htpasswd-php/"
canonical_url: "https://h3manth.com/scribe/reseting-htpasswd-php/"
markdown_url: "https://h3manth.com/scribe/blog/reseting-htpasswd-php.md"
publishDate: "2010-01-15T00:00:00.000Z"
author: "Hemanth HM"
category: "linux"
tags: ["linux","opensource"]
word_count: 189
reading_time_minutes: 1
x_markdown_tokens: 462
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Reseting htpasswd with PHP

> 0) { $htpasswd = file($file); $auth = array(); foreach($htpasswd as $h) { $array = explode(’:’,$h); $user = $array[0]; $pass.

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
";
		return false;
	}

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

	if($status != 0){
		echo "User Password is incorrect!
";
		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 ...
";
		$out = shell_exec($cmd);
		echo "$out";
		echo "Your password has been changed!
";
	}
	else{
		echo "Password doesn't match
";
		exit();
	}
}
?>

## the inputs are passed to the php scripts from a simple HTML form
