Change password php (js) code

I am using next code to register on my page.  And i will also attach login code in a minute. From both of them I need to get change password "php" code.

From login php i need input password field -  logic  where i have to check my existing password and from signup php i need just  two input fields for new password and  conformation of it.

And "submit" button.

Thank you


<?php
// error_reporting(E_ALL);
//ini_set('display_errors', 1);
session_start();
// If user is logged in, header them away
if(isset($_SESSION["username"])){
	header("location: message.php?msg=NO to that weenis");
    exit();
}
?><?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
	include_once("/wp-content/themes/n4/php_includes/db_conx.php");
	$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
	$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
    $query = mysqli_query($db_conx, $sql); 
    $uname_check = mysqli_num_rows($query);
    if (strlen($username) < 3 || strlen($username) > 16) {
	    echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
	    exit();
    }
	if (is_numeric($username[0])) {
	    echo '<strong style="color:#F00;">Usernames must begin with a letter aha</strong>';
	    exit();
    }
    if ($uname_check < 1) {
	    echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
	    exit();
    } else {
	    echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
	    exit();
    }
}
?><?php
// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
	// CONNECT TO THE DATABASE
	include_once("../php_includes/db_conx.php");
	// GATHER THE POSTED DATA INTO LOCAL VARIABLES
	$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
	$e = mysqli_real_escape_string($db_conx, $_POST['e']);
	$p = $_POST['p'];
	$g = preg_replace('#[^a-z]#', '', $_POST['g']);
	$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
	// GET USER IP ADDRESS
    $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
	// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
	$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
    $query = mysqli_query($db_conx, $sql); 
	$u_check = mysqli_num_rows($query);
	// -------------------------------------------
	$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
    $query = mysqli_query($db_conx, $sql); 
	$e_check = mysqli_num_rows($query);
	// FORM DATA ERROR HANDLING
	if($u == "" || $e == "" || $p == "" || $g == "" || $c == ""){
		echo "The form submission is missing values ma kaj.";
        exit();
	} else if ($u_check > 0){ 
        echo "The username you entered is alreay taken";
        exit();
	} else if ($e_check > 0){ 
        echo "That email address is already in use in the system";
        exit();
	} else if (strlen($u) < 3 || strlen($u) > 16) {
        echo "Username must be between 3 and 16 characters";
        exit(); 
    } else if (is_numeric($u[0])) {
        echo 'Username cannot begin with a number';
        exit();
    } else {
	// END FORM DATA ERROR HANDLING
	    // Begin Insertion of data into the database
		// Hash the password and apply your own mysterious unique salt
		
		
		$p_hash = md5($p);
		// Add user info into the database table for the main site table
		$sql = "INSERT INTO users (username, email, password, gender, country, ip, signup, lastlogin, notescheck)       
		        VALUES('$u','$e','$p_hash','$g','$c','$ip',now(),now(),now())";
		$query = mysqli_query($db_conx, $sql); 
		$uid = mysqli_insert_id($db_conx);
		// Establish their row in the useroptions table
		$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
		$query = mysqli_query($db_conx, $sql);
		// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
		    if (!file_exists("../user/$u")) {
			mkdir("../user/$u", 0755);
		}
		  if (!file_exists("../user/$u/projectsList2")) {
			mkdir("../user/$u/projectsList2", 0755);
		}
		// Email the user their activation link
		$to = "$e";							 
		$from = "info@tralaLA.com";
		$subject = 'tralaLA Account Activation';
		$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>3eyeobjects Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><a href="http://www.3eyeobjects.com"><img src="http://www.3eyeobjects.com/wp-content/themes/netobjectnote4/netTestF4/images/logo.png" width="36" height="30" alt="" style="border:none; float:left;"></a>3eyeobjects Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br /><a href="http://www.3eyeobjects.com/wp-content/themes/netobjectnote4/netTestF4/activation.php?id='.$uid.'&u='.$u.'&e='.$e.'&p='.$p_hash.'">Click here to activate your account now</a><br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
		$headers = "From: $from\n";
        $headers .= "MIME-Version: 1.0\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\n";
		mail($to, $subject, $message, $headers);
		echo "signup_success";
		exit();
	}
	exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sign Up</title>

<style type="text/css">
#signupform{
	margin-top:24px;	
}
#signupform > div {
	margin-top: 12px;	
}
#signupform > input,select {
	width: 200px;
	padding: 3px;
	background:#F1F7F4  ;
}
#signupbtn {
	font-size:18px;
	padding: 12px;
}
#terms {
	border:#CCC 1px solid;
	background: #F1F7F4  ;
	padding: 12px;
}
#pageMiddle{
	width: 750px;
	margin: 100px auto;
	height:750px;

}
</style>

<script>
function _(x){
	return document.getElementById(x);
}
function ajaxObj( meth, url ) {
	var x = new XMLHttpRequest();
	x.open( meth, url, true );
	x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	return x;
}
function ajaxReturn(x){
	if(x.readyState == 4 && x.status == 200){
	    return true;	
	}
}
var scrollY = 0;
var distance = 40;
var speed = 24;
function autoScrollTo(el) {
	var currentY = window.pageYOffset;
	var targetY = document.getElementById(el).offsetTop;
	var bodyHeight = document.body.offsetHeight;
	var yPos = currentY + window.innerHeight;
	var animator = setTimeout('autoScrollTo(\''+el+'\')',24);
	if(yPos > bodyHeight){
		clearTimeout(animator);
	} else {
		if(currentY < targetY-distance){
		    scrollY = currentY+distance;
		    window.scroll(0, scrollY);
	    } else {
		    clearTimeout(animator);
	    }
	}
}
function resetScroller(el){
	var currentY = window.pageYOffset;
    var targetY = document.getElementById(el).offsetTop;
	var animator = setTimeout('resetScroller(\''+el+'\')',speed);
	if(currentY > targetY){
		scrollY = currentY-distance;
		window.scroll(0, scrollY);
	} else {
		clearTimeout(animator);
	}
}
////////////////////////////////_______________________________________
function restrict(elem){
	var tf = _(elem);
	var rx = new RegExp;
	if(elem == "email"){
		rx = /[' "]/gi;
	} else if(elem == "username"){
		rx = /[^a-z0-9]/gi;
	}
	tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
	_(x).innerHTML = "";
}
function checkusername(){
	var u = _("username").value;
	if(u != ""){
		_("unamestatus").innerHTML = 'checking ...';
		var ajax = ajaxObj("POST", "signup.php");
        ajax.onreadystatechange = function() {
	        if(ajaxReturn(ajax) == true) {
	            _("unamestatus").innerHTML = ajax.responseText;
	        }
        }
        ajax.send("usernamecheck="+u);
	}
}
function signup(){
	var u = _("username").value;
	var e = _("email").value;
	var p1 = _("pass1").value;
	var p2 = _("pass2").value;
	var c = _("country").value;
	var g = _("gender").value;
	var status = _("status");
	if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == ""){
		status.innerHTML = "Fill out all of the form data";
	} else if(p1 != p2){
		status.innerHTML = "Your password fields do not match";
	} else if( _("terms").style.display == "none"){
		status.innerHTML = "Please view the terms of use";
	} else {
		_("signupbtn").style.display = "none";
		status.innerHTML = 'please wait ...';
		var ajax = ajaxObj("POST", "signup.php");
        ajax.onreadystatechange = function() {
	        if(ajaxReturn(ajax) == true) {
	            if(ajax.responseText != "signup_success"){
					status.innerHTML = ajax.responseText;
					_("signupbtn").style.display = "block";
				} else {
					window.scrollTo(0,0);
					_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
				}
	        }
        }
        ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g);
	}
}
function openTerms(){
	_("terms").style.display = "block";
	emptyElement("status");
}
/* function addEvents(){
	_("elemID").addEventListener("click", func, false);
}
window.onload = addEvents; */
</script>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
  <h3>Sign up to start</h3>
  <form name="signupform" id="signupform" onsubmit="return false;">
    <div>Username: </div>
    <input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
    <span id="unamestatus"></span>
    <div>Email Address:</div>
    <input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
    <div>Create Password:</div>
    <input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
    <div>Confirm Password:</div>
    <input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
    <div>Gender:</div>
    <select id="gender" onfocus="emptyElement('status')">
      <option value=""></option>
      <option value="m">Male</option>
      <option value="f">Female</option>
    </select>
    <div>Country:</div>
    <select id="country" onfocus="emptyElement('status')">
         <option value="No country list ">No country list</option>
         <option value="click here and you are ok ">Click here and you are okay </option>
  //countr list missing  "template_country_list.php" check dfoult file__________________________________________---1.9.
    </select>
    <div>
      <a href="#" onclick="return false" onmousedown="openTerms()">
        View the Terms Of Use
      </a>
    </div>
    <div id="terms" style="display:none;">
      <h3>3eyeObjects terms Of Use</h3>
      <p>1. Play nice here.</p>
     
    </div>
    <br /><br />
    <button id="signupbtn" onclick="signup()">Create Account</button>
    <span id="status"></span>
  </form>
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>

Open in new window

Ivan GolubarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ivan GolubarAuthor Commented:
And here is login code for checking of existing password.

<?php
include_once("../php_includes/check_login_status.php");
// If user is already logged in, header that weenis away
if($user_ok == true){
	header("location: user.php?u=".$_SESSION["username"]);
    exit();
}
?><?php
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["e"])){
	// CONNECT TO THE DATABASE
	include_once("../php_includes/db_conx.php");
	// GATHER THE POSTED DATA INTO LOCAL VARIABLES AND SANITIZE
	$e = mysqli_real_escape_string($db_conx, $_POST['e']);
	$p = md5($_POST['p']);
	// GET USER IP ADDRESS
    $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
	// FORM DATA ERROR HANDLING
	if($e == "" || $p == ""){
		echo "login_failed";
        exit();
	} else {
	// END FORM DATA ERROR HANDLING
		$sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
        $query = mysqli_query($db_conx, $sql);
        $row = mysqli_fetch_row($query);
		$db_id = $row[0];
		$db_username = $row[1];
        $db_pass_str = $row[2];
		if($p != $db_pass_str){
			echo "login_failed";
            exit();
		} else {
			// CREATE THEIR SESSIONS AND COOKIES
			$_SESSION['userid'] = $db_id;
			$_SESSION['username'] = $db_username;
			$_SESSION['password'] = $db_pass_str;
			setcookie("id", $db_id, strtotime( '+30 days' ), "/", "", "", TRUE);
			setcookie("user", $db_username, strtotime( '+30 days' ), "/", "", "", TRUE);
    		setcookie("pass", $db_pass_str, strtotime( '+30 days' ), "/", "", "", TRUE); 
			// UPDATE THEIR "IP" AND "LASTLOGIN" FIELDS
			$sql = "UPDATE users SET ip='$ip', lastlogin=now() WHERE username='$db_username' LIMIT 1";
            $query = mysqli_query($db_conx, $sql);
			echo $db_username;
		    exit();
		}
	}
	exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Log In</title>
<!--<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">-->
<style type="text/css">
#loginform{
	margin-top:24px;	
}
#loginform > div {
	margin-top: 12px;	
}
#loginform > input {
	width: 200px;
	padding: 3px;
	background: #F3F9DD;
}
#loginbtn {
	font-size:15px;
	padding: 10px;
}
#pageMiddle{
	width: 750px;
	margin: 100px auto;
	height:750px;

}
</style>

<script>
function _(x){
	return document.getElementById(x);
}
function ajaxObj( meth, url ) {
	var x = new XMLHttpRequest();
	x.open( meth, url, true );
	x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	return x;
}
function ajaxReturn(x){
	if(x.readyState == 4 && x.status == 200){
	    return true;	
	}
}
var scrollY = 0;
var distance = 40;
var speed = 24;
function autoScrollTo(el) {
	var currentY = window.pageYOffset;
	var targetY = document.getElementById(el).offsetTop;
	var bodyHeight = document.body.offsetHeight;
	var yPos = currentY + window.innerHeight;
	var animator = setTimeout('autoScrollTo(\''+el+'\')',24);
	if(yPos > bodyHeight){
		clearTimeout(animator);
	} else {
		if(currentY < targetY-distance){
		    scrollY = currentY+distance;
		    window.scroll(0, scrollY);
	    } else {
		    clearTimeout(animator);
	    }
	}
}
function resetScroller(el){
	var currentY = window.pageYOffset;
    var targetY = document.getElementById(el).offsetTop;
	var animator = setTimeout('resetScroller(\''+el+'\')',speed);
	if(currentY > targetY){
		scrollY = currentY-distance;
		window.scroll(0, scrollY);
	} else {
		clearTimeout(animator);
	}
}
function emptyElement(x){
	_(x).innerHTML = "";
}
function login(){
	var e = _("email").value;
	var p = _("password").value;
	if(e == "" || p == ""){
		_("status").innerHTML = "Fill out all of the form data";
	} else {
		_("loginbtn").style.display = "none";
		_("status").innerHTML = 'please wait ...';
		var ajax = ajaxObj("POST", "login.php");
        ajax.onreadystatechange = function() {
	        if(ajaxReturn(ajax) == true) {
	            if(ajax.responseText == "login_failed"){
					_("status").innerHTML = "Login unsuccessful, please try again.";
					_("loginbtn").style.display = "block";
				} else {
					//window.location = "user.php?u="+ajax.responseText;
					window.location ="http://www.3eyeobjects.com"
				}
	        }
        }
        ajax.send("e="+e+"&p="+p);
	}
}
</script>
</head>
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
  <h3>Log In Here</h3>
  <!-- LOGIN FORM -->
  <form id="loginform" onsubmit="return false;">
    <div>Email Address:</div>
    <input type="text" id="email" onfocus="emptyElement('status')" maxlength="88">
    <div>Password:</div>
    <input type="password" id="password" onfocus="emptyElement('status')" maxlength="100">
    <br /><br />
    <button id="loginbtn" onclick="login()">Log In</button> 
    <p id="status"></p>
    <a href="forgot_pass.php">Forgot Your Password?</a>
  </form>
  <!-- LOGIN FORM -->
</div>
<?php include_once("template_pageBottom.php"); ?>
</body>
</html>

Open in new window

0
ste5anSenior DeveloperCommented:
Just a comment:

I'm having problems to understand your code. Cause for a security relevant page, it is pretty hard to read. Any login or change password page should be as clean and slim as possible. And using AJAX in such scenarios is pretty scary.
0
Ivan GolubarAuthor Commented:
This code is from 2013.

But this is all i have. Once i will build this app as it is, probably i will search assistance to make it to fit professional standard.

But now let me build functionality to get the picture of what app is doing.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Slick812Commented:
greetings   ivan golubar, , I have Looked at the 2 code pages you have shown here. And I am not sure what kind of HELP you are asking for? ? ?   You have some code that seems to be out dated , not current, and needs would be better if changed to more efficient code, For instance the hash for a password you use is -
      $p_hash = md5($p);

The MD5  hash algorithm is no longer any protection for security, you have to use a stronger security HASH than the old MD5.
Also your AJAX return code could be set up to use more informative user help Data? ?

- - - - - - - - - - -
You say you want  "Change password php (js) code"  , but You do not show your current code that you use for a password change? ? There are very many different ways to set up a password change PHP page, Since the user is already "Signed In" for a password change, you just take the change html FORM submission and first check the password for match, you already have some code that does that with -
$sql = "SELECT id, username, password FROM users WHERE email='$e' AND activated='1' LIMIT 1";
        $query = mysqli_query($db_conx, $sql);
        $row = mysqli_fetch_row($query);
		$db_id = $row[0];
		$db_username = $row[1];
        $db_pass_str = $row[2];
		if($p != $db_pass_str){
	     echo "login_failed";
            exit();
		}

Open in new window


If the password matches then you can do an SQL   UPDATE for that user ID and change the password
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ivan GolubarAuthor Commented:
I don't have "change_pass.php" yet. I need it.

As change password form usually has old_password, new_password and new_password2 input fields, I was thinking to use already written code from login.php (second attached code) for old password task, and code from register,php for new password and for reconfirmation of new password.
0
Slick812Commented:
The thing is that there are many ways to "STYLE" a web page and the Form, so I do not want to write any page HTML code for you, and you already have code in PHP to check and see if the password matches the FORM input text value.
 Maybe you can create a PHP page with the kind of HTML FORM code and style you may need to use, and then try some PHP code to use the existing password submission and check it for a match to the current user? ?
0
Ivan GolubarAuthor Commented:
Next is the form. (from attached code)
I am writing ajax and php. Hope that it will not be a disaster.

<body>
<div id="pageMiddle">
  <h3>Change password form</h3>
  <form name="changePassform" id="changePassformID" onsubmit="return false;">
    <div>Existing password:</div><br />
    <input type="password" id="password" onfocus="emptyElement('status')" maxlength="16">
    <br /><br />
    <div>New password:</div><br />
    <input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
    <br /><br />
    <div>Confirm Password:</div>
    <input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
    <br /><br />
    <button id="submitRequest " onclick="changePass()">Submit request</button>
    <span id="status"></span>
  </form>
</div>
</body>

Open in new window

0
Slick812Commented:
@ ivan golubar
It has been some time since you posted, so I guess you are having trouble? ?
I had some time so I did my version of a Update Password in a database in PHP

Below is the PHP page I used to do this -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
if(!isset($_SESSION["username"])){
	header("location: signup.php");
    exit();
}
$user = $_SESSION["username"];

if(isset($_POST['opw']) && isset($_POST['npw1'])& isset($_POST['npw2'])){
  $opw = $_POST['opw'];
  $npw1 = $_POST['npw1'];
  $npw2 = $_POST['npw2'];
// first check all inputs for 6 length
  if(strlen($opw)< 6 || strlen($npw1)< 6 || strlen($npw2)< 6) {
    echo 'All PassWords must be at least<br />SIX charaters long.';
    exit;
    }

  if ($npw1 !== $npw2) {
    echo 'Your two New Password fields do not match';
    exit;
    }
  include_once("db_conx.php");
  
// check the passwords for match
  if ($result = mysqli_query($db_conx, "SELECT password FROM users WHERE username = '$user'")) {
  $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
  if(mysqli_num_rows($result)) {
// I use a much better Secure Hash with an uncommon 'ripemd256' hash
    $p_hash=base64_encode( hash_hmac('ripemd256', $opw ,'?K9^'.chr(219).'hG3?]F5sawr'.chr(5).'T\Na0167'.chr(177).'}0cL'.chr(3).'x',true) );
    if ($row['password'] === $p_hash) { // check passw match
      $new_hash=base64_encode( hash_hmac('ripemd256', $npw1 ,'?K9^'.chr(219).'hG3?]F5sawr'.chr(5).'T\Na0167'.chr(177).'}0cL'.chr(3).'x',true) );
      if(mysqli_query($db_conx, "UPDATE users SET password = '$new_hash' WHERE username = '$user'")){
      echo '<b>Success</b><br />The Password for '.$user.' has Been Changed';
      exit;} else echo 'ERROR Server Fail: code 4328';
      } else {
      echo '<b>No Match</b><br />The Existing Password for '.$user.' does <br />NOT match What you Submitted.<br />Please Check all your Entries in Existing Password.';
      exit;  
      }
    } else {
    echo 'ERROR for Access User Not Availible. code 721';
    exit;	
    }
  } else echo 'ERROR for Access User Not Availible. code 170';
exit; // make sure you exit the POST no matter what happens
}

?><!doctype html><html><head><meta charset="utf-8"><title>Change Password Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />

<style>
#changePassformID{
  display: inline-block;
  margin-top:10px;
  border: 5px outset #aaa;
  padding: 14px;
  background: #eaefff;
}

#changePassformID > input,select {
  width: 200px;
  padding: 3px;
  background:#F1F7F4;
  margin: 8px 0;
}

#submitRequest {
  font-size:18px;
  padding: 9px;
  cursor: pointer;
}

#pageMiddle{
  width: 750px;
  margin: 3em auto;
  text-align: center;
  padding: 1em;
  border: 1px dotted #aca;
}

#status {
margin-top: 8px;
color: #b60;	
}

</style>

<script>
function _(id){ return document.getElementById(id); }

function emptyElement(id){ document.getElementById(id).innerHTML = ""; }

function changePass() {
var fms = document.forms[0],
    // Get ALL input Values from the forms[0] in an Array
inTests = [ fms.oldpw.value, fms.newpw1.value, fms.newpw2.value ],
    // make a inName to show user which input was bad
inName="Existing Password",
pBad=0,
AjaxOb = 0;
    // check all inputs for length of six
for (var i=0; i< inTests.length; ++i) {
  if (inTests[i].length < 6) {
    switch (i){
        case 1: inName="New Password"; break;
        case 2: inName="Confirm New Password"; break;
      }
    _('status').innerHTML= "The <b>"+inName+"</b> is to short,<br />it must be 6 charaters Long.";
    pBad=1;
    break;
    }
}
if (pBad) return;
if(inTests[1] !== inTests[2]){
  _('status').innerHTML = "Your two New Password fields do not match.";
  return;
  }
    //Create your ajax Object and use the  newPass method
if (!AjaxOb) AjaxOb = new ajaxPost("<?php $_SERVER['SCRIPT_NAME'] ?>");
AjaxOb.newPass(inTests); // send all input values in the inTests array
}


    // The ajaxPost Fuction Below defines The Object Code For Using Ajax
function ajaxPost(url){
  // Include a this.busy to prevent Multiple submissions
this.busy = false;
this.url = url;
var ajax = new XMLHttpRequest();

if(!ajax){
  this.busy = true;
  _('status').innerHTML ='ERROR - Your Web Browser does NOT have<br />the functions to have Ajax work!';return;
  }


this.newPass = function(inAry){
  if(this.busy)return;
  ajax.open('POST', this.url, true);
    // It is nessary to always use encodeURIComponent() for user Input here
  var send2 = 'opw='+encodeURIComponent(inAry[0])+'&npw1='+encodeURIComponent(inAry[1])+'&npw2='+encodeURIComponent(inAry[2]);
  var ajo = this;
  
  ajax.onreadystatechange= function (){
    if(ajax.readyState==4){
      ajo.busy=false;
      if(ajax.status==200){
  // I do not do anything but show but show responce in th status
        _('status').innerHTML = ajax.responseText;	
        } else alert("ERROR - Server Unable to Return: error code: "+ajo.ajax.status);
      }
  } // function onreadystatechange
	
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	this.busy = true;
	ajax.send(send2);}
} // ajaxPost def

</script>

</head>
<body><h3>Change Password Test</h3>
<div id="pageMiddle">
  <h3>Change password for <b><?php echo $user; ?></b></h3>
  <form name="changePassform" id="changePassformID" onsubmit="return false;">
    PassWords Must be at least 6 charaters in length<br /><br />
    Existing Password:<br />
    <input type="password" name="oldpw" onfocus="emptyElement('status')" maxlength="32">
    <br /><br />
    New Password:<br />
    <input name="newpw1" type="password" onfocus="emptyElement('status')" maxlength="32">
    <br /><br />
    Confirm New Password:<br />
    <input name="newpw2" type="password" onfocus="emptyElement('status')" maxlength="32">
    <br /><br />
    <button id="submitRequest" onclick="changePass()">Submit New Password</button>
    <div id="status"></div>
  </form>
</div>
</body></html>

Open in new window


I used some Ajax code that I have done before, I use the function -
     function ajaxPost(url){
as a Container for ALL of the related Ajax operations including the  onreadystatechange method and the  newPass  method, so if there is much more javascript on the Page Then I will know where to find any code realed to ajax.

I have added some code comments to show some info, ask questions if you need more to get this to work for you.
0
Ivan GolubarAuthor Commented:
Thank you.

I have trouble: checking of existing password does not give confirmation.
Is it because of new Secure Hash?

Or must be something other?
0
Slick812Commented:
I changed the Hash, you were using a MD5 hash, which no longer has any security value at all, you may as well not hash it than use the MD5 hash,

As to your results that It will not comfirm the existing pass word. Of Course, it will not since in your database you used the MD5 hash, the 'ripemd256' hash I use will not even come close to a MD5 hash. I thought this would be obvious to you? You should NOT ever use the MD5 hash for securing passwords, you need to change it in your INPUT sign up email and pass word PHP page. If you just want to test this with your current data sets, then just change the two places where there is a HASH, to -

      $p_hash = md5($opw);

and

      $new_hash = md5($npw1);

- - - - - - - - - - - - - -
Do you see what I am doing with the Ajax in the javascript?
0
Ivan GolubarAuthor Commented:
With old hash it works fine. I will have to adapt register, login and forgot_password to new hash. I have some friend already using my app. I will have to notice them to use Forgot_password before Chang_ password.

I did just add option (underlined) to redirect me back to login page.
 echo '<b>Success</b><br />The Password for '.$user.' has Been Changed <br /><a href="login.php">Go to Login page</a>';

I see that you are using checking for "busy".
Later if my app will get interest, I will look for team of professionals to redo all from scratch.

And also one another thing just for curiosity: is there no usual  to prevent user to set old password as new one (to have all three inputs same value)?

Thank you
0
Ivan GolubarAuthor Commented:
I did a mistake i did not assigned points to  best solution, but still to correct participant . Can i leave it as it is?
0
Slick812Commented:
as to -
    "usual  to prevent user to set old password as new one"

You can just test to see if the old one is equal to the new one as in my code for php -
if ($opw === $npw1) {
    echo 'Your New Password can NOT be the same as your Existing Pasword';
    exit;
    }

Or if in javascript, you can test to see if the existing is equal to the new passw.

- - - - - - - - - - - - - - - - - - -

and for -  "not assigned points to  best solution, but still to correct participant . Can i leave it as it is? "

Yes, its OK, the question is closed and I got points

- - - - - - - - - - - - - -

Just a suggestion, , in today's web sites, AJAX is a very very useful thing to use for interactive pages, you might can learn more about AJAX in browser and server code to make your pages better for users
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.