Page 1 of 1

need help with code to change password

Posted: Wed Mar 14, 2012 1:59 pm
by beginner123
For my website I have the option of the user changing their password. They need to enter their username, email, new password and password again. Then I want to change the value for password in the database and replace it with the new password.
Heres the code so far:

Code: Select all

<?php 
//forgot_password2.php
include 'connect.php';
include 'header.php';

if($_SERVER['REQUEST_METHOD'] != 'POST')
{
    echo '<form method="post" action="">
 	 	Enter your Username: <input type="text" name="userName" /><br />
		Enter your E-mail: <input type="email" name="userEmailAddress"><br />
		Enter your new password: <input type="password" name="newPassword"><br />
		Enter Password again: <input type="password" name="userNewPasswordCheck"><br />
 		<input type="submit" value="Change password" />
 	 </form>';
}

else
{
	$errors = array(); 
	//check username
	if(isset($_POST['userName']))
	{	
		$sql = mysql_query("SELECT userID FROM users WHERE userName='".$_POST['userName']."' LIMIT 1");
		$result = mysql_num_rows($sql);
		if ($result != 1) 
		{
			$errors[] =  'Username doesn&prime;t exist';
		}
	}
	else
	{
		$errors[] = 'The username field must not be empty.';
		
	}
	
	//check email address
	if(isset($_POST['userEmailAddress']))
	{	
		$sql = mysql_query("SELECT userID FROM users WHERE userEmailAddress='".$_POST['userEmailAddress']."' LIMIT 1");
		$result = mysql_num_rows($sql);
		if ($result != 1) 
		{
			$errors[] =  'Email address doesn&prime;t exist';
		}
	}
	
	if(!empty($_POST['newPassword']))
	{
		if($_POST['newPassword'] != ($_POST['userNewPasswordCheck']))
		{
			$errors[] = 'The two passwords did not match.';
		}
		if(strlen($_POST['newPassword']) > 45)
		{
			$errors[] = 'The password cannot be longer than 45 characters.';
		}
	}
	else
	{
		$errors[] = 'The password field cannot be empty.';
	}

	if(!empty($errors)) 
	{
		//make sure no fields are empty
		echo 'You must fill in all fields to change your password.<br /><br />';
		echo '<a href="forgot_password2.php">Go back</a>';
		echo '<ul>';
		foreach($errors as $key => $value) 
		{
			echo '<li>' . $value . '</li>'; 
		}
		echo '</ul>';
	}
		else
		{
			$sql = "SELECT 
					userID,
					userName,
					userEmailAddress,
					userPassword
					FROM
						users
					WHERE
						userName = '" . mysql_real_escape_string($_POST['userName']) . "' 
					AND
						userEmailAddress = '" . mysql_real_escape_string($_POST['userEmailAddress']) . "'";
						
						
			$result = mysql_query($sql);
			if(!$result)
			{
				echo 'Something went wrong while changing the password. Please try again later.';
				echo mysql_error(); 
			}
			else
			{
				while($row = mysql_fetch_assoc($result))
					{
						$_SESSION['userID'] 	= $row['userID'];
						$_SESSION['userName'] 	= $row['userName'];
						$_SESSION['userPassword'] = $row['userPassword'];
						$_SESSION['userEmailAddress'] = $row['userEmailAddress'];
					}
				echo 'Your new password is: ' . $_SESSION['userPassword'];
				echo '</br> <a href="signin.php">Sign in</a>';

			}	
		}
	
}

include 'footer.php';
?>
I don't know what code to put in to change the password since right now all it does is display your old password

Re: need help with code to change password

Posted: Wed Mar 14, 2012 2:19 pm
by Celauran
I've made a couple of changes, though they're completely untested. You'll need to read through the file and make a couple of changes yourself before running it.

Code: Select all

<?php

//forgot_password2.php
include 'connect.php';
include 'header.php';

if ($_SERVER['REQUEST_METHOD'] != 'POST')
{
    echo '<form method="post" action="">
                Enter your Username: <input type="text" name="userName" /><br />
                Enter your E-mail: <input type="email" name="userEmailAddress" /><br />
                Enter your old password: <input type="password" name="oldPassword" /><br />
                Enter your new password: <input type="password" name="newPassword" /><br />
                Enter Password again: <input type="password" name="userNewPasswordCheck" /><br />
                <input type="submit" value="Change password" />
         </form>';
}
else
{
    $errors = array();
    if (isset($_POST['userName']) && isset($_POST['userEmailAddress']) && isset($_POST['oldPassword']))
    {
        // A little escaping
        $username = mysql_real_escape_string($_POST['userName']);
        $email    = mysql_real_escape_string($_POST['userEmailAddress']);
        // I don't know how you're hashing your passwords, so I just used a dummy function
        $password = some_hashing_function_here($_POST['oldPassword']);

        // No sense using two queries
        // Should probably make sure they know their old password before allowing them to change it
        $sql    = "SELECT count(userID)
                   FROM users
                   WHERE userName = '{$username}'
                     AND userEmailAddress = '{$email}'
                     AND userPassword = '{$password}'
                   LIMIT 1";
        $count = mysql_fetch_row(mysql_query($sql));
        if ($count != 1)
        {
            $errors[] = 'User not found.';
        }
    }
    else
    {
        $errors[] = 'All fields are required.';
    }

    if (!empty($_POST['newPassword']))
    {
        if ($_POST['newPassword'] != ($_POST['userNewPasswordCheck']))
        {
            $errors[] = 'The two passwords did not match.';
        }
        // Why?
        if (strlen($_POST['newPassword']) > 45)
        {
            $errors[] = 'The password cannot be longer than 45 characters.';
        }
    }
    else
    {
        $errors[] = 'The password field cannot be empty.';
    }

    if (!empty($errors))
    {
        //make sure no fields are empty
        echo 'You must fill in all fields to change your password.<br /><br />';
        echo '<a href="forgot_password2.php">Go back</a>';
        echo '<ul>';
        foreach ($errors as $key => $value)
        {
            echo '<li>' . $value . '</li>';
        }
        echo '</ul>';
    }
    // No errors were found, so we can proceed with password update
    else
    {
        // Need to hash the new password
        $newPass = some_hash_function_here($_POST['newPassword']);
        $sql = "UPDATE users
                SET userPassword = '{$newPass}'
                WHERE
                    userName = '{$username}'
                AND
                    userEmailAddress = '{$email}'";

        $result = mysql_query($sql);
        if (!$result)
        {
            echo 'Something went wrong while changing the password. Please try again later.';
            echo mysql_error();
        }
        else
        {
            while ($row = mysql_fetch_assoc($result))
            {
                $_SESSION['userID']           = $row['userID'];
                $_SESSION['userName']         = $row['userName'];
                // Never store the password in session data
            }
            echo '</br> <a href="signin.php">Sign in</a>';
        }
    }
}

include 'footer.php';
?>

Re: need help with code to change password

Posted: Wed Mar 14, 2012 2:40 pm
by twinedev
A note at the bottom where you (re0assinging the $_SESSION data, you are basing this off of retrieving data from the last query, however it does an update, it doesn't select any data. If you need to actually set these, you can obtain the UserID from the query that validates the entered username/email.

While I agree, don't save the password or the direct hashed copy from the database into the session, I do keep a rehash of it, so that if the password changes, the session is dead. (granted for a lot of projects this is overkill, but consider something such as this. You see someone doing activity under your name, they somehow got logged in as you, so you login, and change the password. Without some type of recheck of the password, as long as the session is alive, they can do what they want with the account unless they get prompted for the password again)

-Greg

Re: need help with code to change password

Posted: Wed Mar 14, 2012 2:48 pm
by Celauran
twinedev wrote:A note at the bottom where you (re0assinging the $_SESSION data, you are basing this off of retrieving data from the last query, however it does an update, it doesn't select any data.
That was my bad. The query was initially a SELECT, not an UPDATE and I forgot to change that last bit. Nice catch.