Link to home
Start Free TrialLog in
Avatar of Sith717
Sith717

asked on

Password reset script doesnt work properly.

Hey guys, I have this problem, I have this password reset script but it doesnt send a new password, it sends the password that was originally in the database instead.

What I want to do, its generate a new password with that salt thing I guess.

Here is the code:

<?php

function checkUNEmail($uname,$email)
{
	global $mySQL;
	$userID = 'X';
	$error = array('status'=>false,'userID'=>0);
	if (isset($email) && trim($email) != '') {
		//email was entered
		if ($SQL = $mySQL->prepare("SELECT `ID` FROM `users` WHERE `Email` = ? LIMIT 1"))
		{
			$SQL->bind_param('s',trim($email));
			$SQL->execute();
			$SQL->store_result();
			$numRows = $SQL->num_rows();
			$SQL->bind_result($userID);
			$SQL->fetch();
			$SQL->close();
			if ($numRows >= 1) return array('status'=>true,'userID'=>$userID);
		} else { return $error; }
	} elseif (isset($uname) && trim($uname) != '') {
		//username was entered
		if ($SQL = $mySQL->prepare("SELECT `ID` FROM users WHERE Username = ? LIMIT 1"))
		{
			$SQL->bind_param('s',trim($uname));
			$SQL->execute();
			$SQL->store_result();
			$numRows = $SQL->num_rows();
			$SQL->bind_result($userID);
			$SQL->fetch();
			$SQL->close();
			if ($numRows >= 1) return array('status'=>true,'userID'=>$userID);
		} else { return $error; }
	} else {
		//nothing was entered;
		return $error;
	}
}

function getSecurityQuestion($userID)
{
	global $mySQL;
	$questions = array();
	$questions[0] = "What is your mother's maiden name?";
	$questions[1] = "What city were you born in?";
	$questions[2] = "What is your favorite color?";
	$questions[3] = "What year did you graduate from High School?";
	$questions[4] = "What was the name of your first boyfriend/girlfriend?";
	$questions[5] = "What is your favorite model of car?";
	if ($SQL = $mySQL->prepare("SELECT `secQ` FROM `users` WHERE `ID` = ? LIMIT 1"))
	{
		$SQL->bind_param('i',$userID);
		$SQL->execute();
		$SQL->store_result();
		$SQL->bind_result($secQ);
		$SQL->fetch();
		$SQL->close();
		return $questions[$secQ];
	} else {
		return false;
	}
}

function checkSecAnswer($userID,$answer)
{
	global $mySQL;
	if ($SQL = $mySQL->prepare("SELECT `Username` FROM `users` WHERE `ID` = ? AND LOWER(`secA`) = ? LIMIT 1"))
	{
		$answer = strtolower($answer);
		$SQL->bind_param('is',$userID,$answer);
		$SQL->execute();
		$SQL->store_result();
		$numRows = $SQL->num_rows();
		$SQL->close();
		if ($numRows >= 1) { return true; }
	} else {
		return false;
	}
}

function sendPasswordEmail($userID)
{
	global $mySQL;
	if ($SQL = $mySQL->prepare("SELECT `Username`,`Email`,`Password` FROM `users` WHERE `ID` = ? LIMIT 1"))
	{
		$SQL->bind_param('i',$userID);
		$SQL->execute();
		$SQL->store_result();
		$SQL->bind_result($uname,$email,$password);
		$SQL->fetch();
		$SQL->close();
		$message = "Dear $uname,\r\n";
		$message .= "Here is your requested lost password for your account at our site:\r\n";
		$message .= "-----------------------\r\n";
		$message .= "$password\r\n";
		$message .= "-----------------------\r\n";
		$message .= "Our login page: <a href=\"login.php\">http://www.oursite.com/login.php</a>\r\n\r\n";
		$message .= "Thanks,\r\n";
		$message .= "-- Our site team";
		$headers .= "From: Our Site <webmaster@oursite.com> \n";
		$headers .= "To-Sender: \n";
		$headers .= "X-Mailer: PHP\n"; // mailer
		$headers .= "Reply-To: webmaster@oursite.com\n"; // Reply address
		$headers .= "Return-Path: webmaster@oursite.com\n"; //Return Path for errors
		$headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
		$subject = "Your Lost Password";
		@mail($email,$subject,$message,$headers);
		return str_replace("\r\n","<br/ >",$message);
	}
}

?>

Open in new window



Instead of emailing the same password I want it to generate a random string, update the database with that string and email me that same string.

I think it would be for better security.

Here is the script I want to integrate into it:

 
function genRandomString() {
    $length = 10;
    $characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
    $string = ”;    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}

Open in new window



---

Thanks for the help ahead of time, I will give many points to whoever can help me the best :)
ASKER CERTIFIED SOLUTION
Avatar of designsevolved
designsevolved
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sith717
Sith717

ASKER

Where would I actually integrate that code?

Can you give me a final code of how it looks with it inside please.

Il solve the problem after so you can get the points.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sith717

ASKER

For some reason it wont work...

I took the code that you did and it wont work for some reason...

I have really no idea.

Can you go over the code and see what maybe the problem is?

Here is an example of where I am adding the code.


http://runescape-beta.org/login/files/password/forgotPass.php

Use the email: y.anille@yahoo.com

Use the secret code answer as: Sydney  (CaPiTaLs MATTER!)

The original password is envato, and it should change it but it doesnt...

Here is the contents of forgotPass.php

 
<?php //unencrypted password example
include("assets/php/database.php"); 
include("assets/php/functions.php");
$show = 'emailForm'; //which form step to show by default
if ($_SESSION['lockout'] == true && (mktime() > $_SESSION['lastTime'] + 900))
{
	$_SESSION['lockout'] = false;
	$_SESSION['badCount'] = 0;
}
if (isset($_POST['subStep']) && $_SESSION['lockout'] != true)
{
	switch($_POST['subStep'])
	{
		case 1:
			//we just submitted an email or username for verification
			$result = checkUNEmail($_POST['uname'],$_POST['email']);
			if ($result['status'] == false )
			{
				$error = true;
				$show = 'userNotFound';
			} else {
				$error = false;
				$show = 'securityForm';
				$securityUser = $result['userID'];
			}
		break;
		case 2:
			//we just submitted the security question for verification
			if ($_POST['userID'] != "" && $_POST['answer'] != "")
			{
				$result = checkSecAnswer($_POST['userID'],$_POST['answer']);
				if ($result == true)
				{
					//answer was right
					$error = false;
					$show = 'successPage';
					$passwordMessage = sendPasswordEmail($_POST['userID']);
					$_SESSION['badCount'] = 0;
				} else {
					//answer was wrong
					$error = true;
					$show = 'securityForm';
					$securityUser = $_POST['userID'];
					$_SESSION['badCount']++;
				}
			} else {
				$error = true;
				$show = 'securityForm';
			}
		break;
	}
}
if ($_SESSION['badCount'] >= 3)
{
	$show = 'speedLimit';
	$_SESSION['lockout'] = true;
	$_SESSION['lastTime'] = '' ? mktime() : $_SESSION['lastTime'];
}
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Password Recovery</title>
<link href="../assets/css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="header"></div>
<div id="page">
	<?php if ($show == 'emailForm') { ?>
	<h2>Password Recovery</h2>
    <p>You can use this form to recover your password if you have forgotten it. Enter either your username or your email address below to get started.</p>
    <?php if ($error == true) { ?><span class="error">You must enter either a username or password to continue.</span><?php } ?>
    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
        <div class="fieldGroup"><label for="uname">Username</label><div class="field"><input type="text" name="uname" id="uname" value="" maxlength="20"></div></div>
        <div class="fieldGroup"><label>- OR -</label></div>
        <div class="fieldGroup"><label for="email">Email</label><div class="field"><input type="text" name="email" id="email" value="" maxlength="255"></div></div>
        <input type="hidden" name="subStep" value="1" />
        <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
        <div class="clear"></div>
    </form>
    <?php } elseif ($show == 'securityForm') { ?>
    <h2>Password Recovery</h2>
    <p>Please answer the security question below:</p>
    <?php if ($error == true) { ?><span class="error">You must answer the security question correctly to receive your lost password.</span><?php } ?>
    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
        <div class="fieldGroup"><label>Question</label><div class="field"><?= getSecurityQuestion($securityUser); ?></div></div>
        <div class="fieldGroup"><label for="answer">Answer</label><div class="field"><input type="text" name="answer" id="answer" value="" maxlength="255"></div></div>
        <input type="hidden" name="subStep" value="2" />
        <input type="hidden" name="userID" value="<?= $securityUser; ?>" />
        <div class="fieldGroup"><input type="submit" value="Submit" style="margin-left: 150px;" /></div>
        <div class="clear"></div>
    </form>
    <?php } elseif ($show == 'userNotFound') { ?>
    <h2>Password Recovery</h2>
    <p>The username or email you entered was not found in our database.</p>
    <?php } elseif ($show == 'successPage') { ?>
    <h2>Password Recovery</h2>
    <p>Your password has been mailed to you. You should receive an email in a few moments with your password in it. <strong>(Mail will not send unless you have an smtp server running locally.)</strong><br /><br /><a href="login.php">Return</a> to the login page. </p>
    <p>This is the message that would appear in the email:</p>
    <div class="message"><?= $passwordMessage;?></div>
    <?php } elseif ($show == 'speedLimit') { ?>
    <h2>Warning</h2>
    <p>You have answered the security question wrong too many times. You will be locked out for 15 minutes, after which you can try again.</p><br /><br /><a href="login.php">Return</a> to the login page. </p>
    <?php } ?>
</div>
</body>
</html>
<?php
	ob_flush();
	$mySQL->close();
?>

Open in new window



Here is the contents of functions.php

 
<?php

function checkUNEmail($uname,$email)
{
	global $mySQL;
	$userID = 'X';
	$error = array('status'=>false,'userID'=>0);
	if (isset($email) && trim($email) != '') {
		//email was entered
		if ($SQL = $mySQL->prepare("SELECT `ID` FROM `users` WHERE `Email` = ? LIMIT 1"))
		{
			$SQL->bind_param('s',trim($email));
			$SQL->execute();
			$SQL->store_result();
			$numRows = $SQL->num_rows();
			$SQL->bind_result($userID);
			$SQL->fetch();
			$SQL->close();
			if ($numRows >= 1) return array('status'=>true,'userID'=>$userID);
		} else { return $error; }
	} elseif (isset($uname) && trim($uname) != '') {
		//username was entered
		if ($SQL = $mySQL->prepare("SELECT `ID` FROM users WHERE Username = ? LIMIT 1"))
		{
			$SQL->bind_param('s',trim($uname));
			$SQL->execute();
			$SQL->store_result();
			$numRows = $SQL->num_rows();
			$SQL->bind_result($userID);
			$SQL->fetch();
			$SQL->close();
			if ($numRows >= 1) return array('status'=>true,'userID'=>$userID);
		} else { return $error; }
	} else {
		//nothing was entered;
		return $error;
	}
}

function getSecurityQuestion($userID)
{
	global $mySQL;
	$questions = array();
	$questions[0] = "What is your mother's maiden name?";
	$questions[1] = "What city were you born in?";
	$questions[2] = "What is your favorite color?";
	$questions[3] = "What year did you graduate from High School?";
	$questions[4] = "What was the name of your first boyfriend/girlfriend?";
	$questions[5] = "What is your favorite model of car?";
	if ($SQL = $mySQL->prepare("SELECT `secQ` FROM `users` WHERE `ID` = ? LIMIT 1"))
	{
		$SQL->bind_param('i',$userID);
		$SQL->execute();
		$SQL->store_result();
		$SQL->bind_result($secQ);
		$SQL->fetch();
		$SQL->close();
		return $questions[$secQ];
	} else {
		return false;
	}
}

function checkSecAnswer($userID,$answer)
{
	global $mySQL;
	if ($SQL = $mySQL->prepare("SELECT `Username` FROM `users` WHERE `ID` = ? AND LOWER(`secA`) = ? LIMIT 1"))
	{
		$answer = strtolower($answer);
		$SQL->bind_param('is',$userID,$answer);
		$SQL->execute();
		$SQL->store_result();
		$numRows = $SQL->num_rows();
		$SQL->close();
		if ($numRows >= 1) { return true; }
	} else {
		return false;
	}
}

function sendPasswordEmail($userID)
{
	global $mySQL;
	if ($SQL = $mySQL->prepare("SELECT `Username`,`Email`,`Password` FROM `users` WHERE `ID` = ? LIMIT 1"))
	{
		$SQL->bind_param('i',$userID);
		$SQL->execute();
		$SQL->store_result();
		$SQL->bind_result($uname,$email,$password);
		$SQL->fetch();
		$SQL->close();
		$message = "Dear $uname,\r\n";
		$message .= "Here is your requested lost password for your account at our site:\r\n";
		$message .= "-----------------------\r\n";
		$message .= "$password\r\n";
		$message .= "-----------------------\r\n";
		$message .= "Our login page: <a href=\"login.php\">http://www.oursite.com/login.php</a>\r\n\r\n";
		$message .= "Thanks,\r\n";
		$message .= "-- Our site team";
		$headers .= "From: Our Site <webmaster@oursite.com> \n";
		$headers .= "To-Sender: \n";
		$headers .= "X-Mailer: PHP\n"; // mailer
		$headers .= "Reply-To: webmaster@oursite.com\n"; // Reply address
		$headers .= "Return-Path: webmaster@oursite.com\n"; //Return Path for errors
		$headers .= "Content-Type: text/html; charset=iso-8859-1"; //Enc-type
		$subject = "Your Lost Password";
		@mail($email,$subject,$message,$headers);
		return str_replace("\r\n","<br/ >",$message);
	}
}

function genRandomString() {
    $length = 10;
    $characters = ’0123456789abcdefghijklmnopqrstuvwxyz’;
    $string = ”;    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}

function changePassword($userID){
  $password = genRandomString();
  mysql('UPDATE `users` SET `Password`="'.$password.'" WHERE `ID`="'.$userID.'" LIMIT 1');
  return $password;
}

?>

Open in new window


I dont think the code to update the password is being executed...

Thanks for the help and taking your time.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sith717

ASKER

Okay, so with that code, what would be the final PHP code that it should look like, I really appreciate your help.

I will be giving you the 500 points for the help that you provided.

Thanks again.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sith717

ASKER

The script doesnt seem to work, the page goes white and these are the errors that appear.

 
Notice: Use of undefined constant ’0123456789abcdefghijklmnopqrstuvwxyz’ - assumed '’0123456789abcdefghijklmnopqrstuvwxyz’' in /home/t2n7gauf/public_html/login/files/password/assets/php/functions2.php on line 122

Notice: Use of undefined constant ” - assumed '”' in /home/t2n7gauf/public_html/login/files/password/assets/php/functions2.php on line 123

Notice: Uninitialized string offset: 42 in /home/t2n7gauf/public_html/login/files/password/assets/php/functions2.php on line 126

Notice: Uninitialized string offset: 42 in /home/t2n7gauf/public_html/login/files/password/assets/php/functions2.php on line 126

Notice: Undefined variable: mySQL in /home/t2n7gauf/public_html/login/files/password/assets/php/functions2.php on line 134

Fatal error: Call to a member function prepare() on a non-object in /home/t2n7gauf/public_html/login/files/password/assets/php/functions2.php on line 134

Open in new window



Why is that?

I really have no idea why it is giving me that error.

If you are able to fix it, please do. :)
Avatar of Sith717

ASKER

Bump. This is important.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sith717

ASKER

Okay, but for some reason it still wont reset the password to a randomly generated one... :(

Any reason why?

It still keeps the old password.

I really would love for it to be changing the password in the database and email it to me.

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sith717

ASKER

Thanks, il try it out, is there any way to recode it so in a way its more understandable?
Avatar of Sith717

ASKER

I tried that code and if gives me these errors:

 
Notice: Uninitialized string offset: 36 in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 128

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 't2n7gauf'@'localhost' (using password: NO) in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 136

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 136

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 't2n7gauf'@'localhost' (using password: NO) in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 136

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 136

Warning: mysql_query() [function.mysql-query]: Access denied for user 't2n7gauf'@'localhost' (using password: NO) in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 136

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 136

Notice: Undefined variable: headers in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 110

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sith717

ASKER

Okay, there are 2 errors remaining...


 
Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of variables doesn't match number of parameters in prepared statement in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 136

Notice: Undefined variable: headers in /home/t2n7gauf/public_html/login/files/password/assets/php/functions3.php on line 108

Open in new window


The first error iv never seen im my life.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sith717

ASKER

Thanks everyone