Post: PHP Change Password ISSUE MYSQL
10-17-2011, 07:40 PM #1
(adsbygoogle = window.adsbygoogle || []).push({}); Here is the script ive been making. everything seems to work, but it doesn't update the users password.

    
<?php
$host="****SECRET*****"; // Host name
$username="****SECRET****"; // Mysql username
$password="****SECRET****"; // Mysql password
$db_name="****SECRET*****"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

//take the username and prevent SQL injections
$username = mysql_real_escape_string($username);

//variables for new/old passess
$newpass = $_POST['newpass'];
$confirmpass = $_POST['confirmpass'];
$id = $POST['id'];

//sure proof denies
$count = 0;

//Checks for the cookie
if (isset($_COOKIE["mycookie"])) {
$count = 1;
} else {
$count = 0;
}

// If result matched $myusername and $mypassword, table row must be 1 row

if ($count==1) {
setcookie('mycookie', 'Test mycookie', time()+3600*24);

//display all users
$display = mysql_query("SELECT * FROM members ORDER BY ID");

//begin the query
$sql = mysql_query("SELECT * FROM $tbl_name WHERE username = '".$username."' LIMIT 1");

//acutal shit
if (isset($_POST['password']))

{
//Prevent SQL injections
$username = mysql_real_escape_string($_POST['username']);

//Get MD5 hash of password
$password = sha256(md5(sha1(sha512(mysql_real_escape_string($_POST['password'])))));

//Check to see if username exists
$sql = ("SELECT * FROM $tbl_name WHERE password = '".$password."' ");
$result = mysql_query($sql);

if (mysql_num_rows($result) < 1) {
echo "That is not your current password";
} else {
if ($confirmpass==$newpass) {
$querynew = ("UPDATE $tbl_name SET password='$newpass' WHERE id='$session[id]'");
$resultnew = mysql_query($querynew) or die(mysql_error());
echo "Password changed!";
} else {
echo "Passwords Do not match!";
}
}
} else {
echo "Change your password";
}

echo "`
<html></html>
<a href='index.php'>Go Back</a>
<center>
<table>
<form action='change.php' method='post'>
<tr><td>Current Password:</td><td><input name='password' type='text' /></tr></td><br />
<tr><td>New Password:</td><td><input name='newpass' type='text' /></td></tr><br />
<tr><td>Confirm Password:</td><td><input name='confirmpass' type='text' /></td></tr><br />
<tr><td><input type='submit' value='Change Password' /></td></tr>
</table>
</form>
</center>
";

//html for display all users
echo "<center><table border='1'>
<tr>
<th>UserName</th>
<th>ID</th>
</tr>";

while($row = mysql_fetch_array($display))
{
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "</tr>";
}
echo "</table></center>";


} else {
echo "You do not have permissions on this page!";
}
?>


In that script you can see that it shows the users and id's of them.

it also displays a form that has to enter the current password, and if it's not right it won't do anything, and then the new passwords have to match to do the process. now the actually update script itself.

$querynew = ("UPDATE $tbl_name SET password='$newpass' WHERE id='$session[id]'");
$resultnew = mysql_query($querynew) or die(mysql_error());

now that SHOULD update the memebers table to the user that is logged in (admin) and change the password with the one posted in the form.

now what's wrong with that script?
(adsbygoogle = window.adsbygoogle || []).push({});
10-18-2011, 04:55 AM #11
okay here is the final script ive come up with. I will be reading way more into sql and php. just for the time being can you get this so only the user logged in can change their own password?


    
<?php
$host="******"; // Host name
$username="*****"; // Mysql username
$password="*****"; // Mysql password
$db_name="****"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

//take the username and prevent SQL injections
$username = mysql_real_escape_string($username);

//variables for new/old passess
$newpass = $_POST['newpass'];
$confirmpass = $_POST['confirmpass'];

//this is the password that will be changed!
$finalpass = sha1(md5(sha1(sha1($newpass))));

//sure proof denies unless has cookie
$count = 0;

//Checks for the cookie, or deny access
if (isset($_COOKIE["mycookie"])) {
$count = 1;
} else {
$count = 0;
}

//select id from table
$select = mysql_query("SELECT id FROM $tbl_name WHERE username = '.$username.' ");

//start session
session_start();
$_SESSION['id'] = $select['id']; //store the resulting id as a session variable

// If result matched $myusername and $mypassword, table row must be 1 row

// sets cookie if cookie is found

if ($count==1) {
setcookie('mycookie', 'Test mycookie', time()+3600*24);
echo "You may only change your password!";
//display all users
$display = mysql_query("SELECT * FROM members ORDER BY ID");

//begin the query
$sql = mysql_query("SELECT * FROM $tbl_name WHERE username = '".$username."' LIMIT 1");

//If password is set then check if correct
if (isset($_POST['password']))

{
//Prevent SQL injections
$username = mysql_real_escape_string($_POST['username']);

// UPDATE NEW PASSWORD with the same encryption as the database
$password = sha1(md5(sha1(sha1(mysql_real_escape_string($_POST['password'])))));

//Check to see if username exists
$sql = ("SELECT * FROM $tbl_name WHERE password = '".$password."' ");
$result = mysql_query($sql);

if (mysql_num_rows($result) < 1) {
echo "That is not your current password";
} else {
if ($confirmpass==$newpass) {
session_start();
$querynew = mysql_query("UPDATE $tbl_name SET password = '".$finalpass."' WHERE username = '".$username."' LIMIT 1"); // run the update query
echo "Password changed!";
} else {
echo "Passwords Do not match!";
}
}
} else {
echo "Change your password";
}

echo "
<a href='index.php'>Go Back</a>
<center>
<table>
<form action='change.php' method='post'>
<tr><td>Your Username:</td><td><input name='username' type='text' /></tr></td><br />
<tr><td>Current Password:</td><td><input name='password' type='text' /></tr></td><br />
<tr><td>New Password:</td><td><input name='newpass' type='text' /></td></tr><br />
<tr><td>Confirm Password:</td><td><input name='confirmpass' type='text' /></td></tr><br />
<tr><td><input type='submit' value='Change Password' /></td></tr>
</table>
</form>
</center>
";

//html for display all users
echo "<center><table border='1'>
<tr>
<th>UserName</th>
<th>ID</th>
</tr>";

while($row = mysql_fetch_array($display))
{
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "</tr>";
}
echo "</table></center>";


} else {
echo "You do not have permissions on this page!";
}
?>



so that works, but you have to enter the user's name and changes their password. could I set it up like this?

$loggedinuser = ($_REQUEST['$username']);

then

    
if $username==$loggedinuser
{
password changed!
}
else
{
Cannot change another users password!
}


that's probably wrong, but the only way I think of the way.

my login system doesn't use sessions it queries the database, and if the username & password from the form are equal to the one queried in the database it allows access. now this is very hard on my point of view without the use of sessions. so is there any other way around this??
10-18-2011, 06:54 AM #12
Epic?
Awe-Inspiring
Originally posted by jp4priest View Post
okay here is the final script ive come up with. I will be reading way more into sql and php. just for the time being can you get this so only the user logged in can change their own password?


    
<?php
$host="******"; // Host name
$username="*****"; // Mysql username
$password="*****"; // Mysql password
$db_name="****"; // Database name
$tbl_name="members"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

//take the username and prevent SQL injections
$username = mysql_real_escape_string($username);

//variables for new/old passess
$newpass = $_POST['newpass'];
$confirmpass = $_POST['confirmpass'];

//this is the password that will be changed!
$finalpass = sha1(md5(sha1(sha1($newpass))));

//sure proof denies unless has cookie
$count = 0;

//Checks for the cookie, or deny access
if (isset($_COOKIE["mycookie"])) {
$count = 1;
} else {
$count = 0;
}

//select id from table
$select = mysql_query("SELECT id FROM $tbl_name WHERE username = '.$username.' ");

//start session
session_start();
$_SESSION['id'] = $select['id']; //store the resulting id as a session variable

// If result matched $myusername and $mypassword, table row must be 1 row

// sets cookie if cookie is found

if ($count==1) {
setcookie('mycookie', 'Test mycookie', time()+3600*24);
echo "You may only change your password!";
//display all users
$display = mysql_query("SELECT * FROM members ORDER BY ID");

//begin the query
$sql = mysql_query("SELECT * FROM $tbl_name WHERE username = '".$username."' LIMIT 1");

//If password is set then check if correct
if (isset($_POST['password']))

{
//Prevent SQL injections
$username = mysql_real_escape_string($_POST['username']);

// UPDATE NEW PASSWORD with the same encryption as the database
$password = sha1(md5(sha1(sha1(mysql_real_escape_string($_POST['password'])))));

//Check to see if username exists
$sql = ("SELECT * FROM $tbl_name WHERE password = '".$password."' ");
$result = mysql_query($sql);

if (mysql_num_rows($result) < 1) {
echo "That is not your current password";
} else {
if ($confirmpass==$newpass) {
session_start();
$querynew = mysql_query("UPDATE $tbl_name SET password = '".$finalpass."' WHERE username = '".$username."' LIMIT 1"); // run the update query
echo "Password changed!";
} else {
echo "Passwords Do not match!";
}
}
} else {
echo "Change your password";
}

echo "
<a href='https://www.nextgenupdate.com/forums/'>Go Back</a>
<center>
<table>
<form action='change.php' method='post'>
<tr><td>Your Username:</td><td><input name='username' type='text' /></tr></td><br />
<tr><td>Current Password:</td><td><input name='password' type='text' /></tr></td><br />
<tr><td>New Password:</td><td><input name='newpass' type='text' /></td></tr><br />
<tr><td>Confirm Password:</td><td><input name='confirmpass' type='text' /></td></tr><br />
<tr><td><input type='submit' value='Change Password' /></td></tr>
</table>
</form>
</center>
";

//html for display all users
echo "<center><table border='1'>
<tr>
<th>UserName</th>
<th>ID</th>
</tr>";

while($row = mysql_fetch_array($display))
{
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['id'] . "</td>";
echo "</tr>";
}
echo "</table></center>";


} else {
echo "You do not have permissions on this page!";
}
?>



so that works, but you have to enter the user's name and changes their password. could I set it up like this?

$loggedinuser = ($_REQUEST['$username']);

then

    
if $username==$loggedinuser
{
password changed!
}
else
{
Cannot change another users password!
}


that's probably wrong, but the only way I think of the way.

my login system doesn't use sessions it queries the database, and if the username & password from the form are equal to the one queried in the database it allows access. now this is very hard on my point of view without the use of sessions. so is there any other way around this??


It seems to me like you have a few things confused. Here's the process flow for this script in specific:

  1. Check if the user is logged in. If the user is NOT logged in, redirect them to a log-in form. Otherwise, continue with the script...
  2. Show the password change form
  3. On the submission of the password change form, run a query UPDATE the user's table and SET the password field to the new password only WHERE the user's ID (stored in a database) matches the user's ID (stored in a session), LIMIT this to only 1 update
  4. Lastly, notify the user of a successful change


Now, let's go through and implement all of these steps.

First off, at the beginning of our script, we need to check if the user is logged in or not:
    <?php
session_start();

// checks if either the username or user_id values are NOT set
if (!isset($_SESSION['username']) || !isset($_SESSION['user_id']))
{
header('Location: login_form.php'Winky Winky; // redirect to login form
die(); // kill the script
}
else
{
// the following query will verify whether or not the username is also legitimate
$query = mysql_query('SELECT username FROM users WHERE user_id = ' . mysql_real_escape_string($_SESSION['user_id']));
if (mysql_num_rows($query) > 1 || mysql_num_rows($query) <= 0) // check if more than one, or less than one user exists
{
die('There has been an error, please return to the log in form'Winky Winky;
}
else
{
$result = mysql_fetch_assoc($query);
if ($result['username'] != $_SESSION['username']) // check if the usernames match
{
die('There has been an error, please return to the log in form'Winky Winky;
}
}
}
?>


Step two, we display the log in form. Your login form can look roughly like:
    <html>
<head>
<title>Change Your Password</title>
</head>
<body>
<form action="changepassword.php" method="post">
<label for="originalpassword">Current password:</label><input type="password" id="orginalpassword" name="originalpassword" />
<br />
<label for="newpassword">New password:</label><input type="password" id="newpassword" name="newpassword" />
<br />
<label for="confirmpassword">Confirm password:</label><input type="password" id="confirmpassword" name="confirmpassword" />
<br />
<input type="submit" name="submit" value="Change Password" />
</form>
</body>
</html>


As you can see in the above code, this is a very simple form, we have the user enter their old/current password (for confirmation), then the new password (and then we have them re-enter the new password for confirmation). As you can see, in the form, we specified "changepassword.php" as the action. This means, that when the form is submitted, all the data will be sent via POST to the changepassword.php file, thus allowing the changepassword.php file to act like a script to change the password.

Now, we can move on to step three. Remember, step three involved us updating the user's password. For this, let's create a new file that's separate from our HTML form (this HTML form also contains the code to verify that our user is actually logged in). Let's get to step three. If you recall, in step two, we specified changepassword.php as the action, therefore, we'll create a new file by the name of changepassword.php, this will be the script that actually updates the password.

Here's our script:
    <?php
session_start();

// first confirm whether or not the two passwords match
if ($_POST['newpassword'] != $_POST['confirmpassword'])
{
echo 'The passwords you entered don\'t match! Go back and try again!<meta http-equiv="refresh" content="3; url=newpasswordform.php">';
die();
}

// next, determine if the old password is correct
// note that you'll also need to apply whatever hashing functions you used to store the password originally, apply those functions in the line of code below:
$old_password = mysql_real_escape_string($_POST['originalpassword']);

// we'll then proceed to query the database, we'll select the password field from the users table where the user_id (stored in the session variable) matches
$query = mysql_query("SELECT password FROM users WHERE user_id=$_SESSION['user_id']");

// fetch the results of the query as an associative array:
$result = mysql_fetch_assoc($query);

// after that, compare the two passwords:
if ($old_password != $result['password'])
{
echo 'Your original password was incorrect! Go back and try again!<meta http-equiv="refresh" content="3; url=newpasswordform.php" />';
die();
}

// finally, we'll get to the point of actually making the change
// first, we'll prepare our new password, again, be sure to apply all proper hashing functions to the line of code below:
$new_password = mysql_real_escape_string($_POST['newpassword']);

// second, we will query: we update the users table to set the password equal to the new password, we'll only do this where the user_ids match, and we'll limit this to one update
$query = mysql_query("UPDATE users SET password='" . $new_password . "' WHERE user_id = " . $_SESSION['user_id'] . " LIMIT 1");

if ($query) // if the update is a success
{
echo 'Password successfully updated! You\'re now being redirected back to the index page!<meta http-equiv="refresh" content="3; url=index.php" />';
}
else // if the update fails
{
echo 'Failed to update!';
}
?>


That should work for you, of course, what I posted isn't totally secure (there are a couple of holes), but I'm sure you can spot them and easily patch them!

The following user thanked Epic? for this useful post:

10-18-2011, 11:55 PM #13
yeah it works all good now, but 1 more thing is a session basically a temporary server cookie??

makes way more sence(fail) thnx a lot Smile
10-19-2011, 01:16 AM #14
Epic?
Awe-Inspiring
Originally posted by jp4priest View Post
yeah it works all good now, but 1 more thing is a session basically a temporary server cookie??

makes way more sence(fail) thnx a lot Smile


A session is referred to as a session cookie, and functions similar to a cookie.

The differences are this:

Sessions are stored on the server, cookies are stored with the client/user (its stored in browser data files).
Values in cookies can be manipulated by the user, since they are stored with the user, whereas sessions cannot be directly manipulated by the user since they are stored on the server (note that there is an attack known as session hijacking, and you can Google it if you want).
Sessions only last until the browser disconnects from the server by closing his or her browser (hence the name "session" since sessions only last for one browsing session). Cookies can function in the same way (expire after the browser closes), however, in a typical situation, cookies can last for an indefinite amount of time (meaning that even once the browser is closed the cookie still exists, and the data stored within the cookie is still accessible by the website once the user reconnects to the website).

Note that you may also want to read You must login or register to view this content..

Basically, here's what you need to know. Users can mess with cookies (so always sanitize them and check the values stored within them), but users can't really mess with sessions. Cookies are used to store long-term information (lasts even once the browser has closed), whereas sessions are used to store short-term information (once the browser closes, the data is gone).

Don't take this harshly, but you really ought to read a book pertaining to PHP, SQL, and web development (or something along those lines). I don't mean any offense by this, but I did have to practically write the script for you to finally understand, and I also had to cover some extremely basic topics. Whatever you're learning from now, ditch it for something better. Albeit, You must login or register to view this content. may not be the best site, but its a free resource and has a lot of content on web development, you really ought to read through that. If spending money (or hunting down a free download) is something that interests you, I can point you to a few good books or online classes.

As always, if you have any further questions, let me know.
10-19-2011, 01:41 AM #15
actually I knew most of the stuff, you just kinda rambled on and I didn't want to interupt you. :p

but I didn't know about sessions that much, and that cleared up for me so thnx for that lol!
10-19-2011, 02:38 AM #16
Epic?
Awe-Inspiring
Originally posted by River
actually I knew most of the stuff, you just kinda rambled on and I didn't want to interupt you. :p

but I didn't know about sessions that much, and that cleared up for me so thnx for that lol!


If you knew most of this stuff, then why'd you ask such a basic question in the first place? And why didn't you reread my first answer? My first one (or two) posts to this thread pretty much solved your problem accurately (I've just been repeating myself).
10-20-2011, 02:26 AM #17
Originally posted by Epic
If you knew most of this stuff, then why'd you ask such a basic question in the first place? And why didn't you reread my first answer? My first one (or two) posts to this thread pretty much solved your problem accurately (I've just been repeating myself).


well the way I set my login is wierd. I didn't use sessions at all and it was one of those ghetto login things.

anyway thanks for showing me stuff i didn't know. Smile

back to mw2 section >Smile
10-20-2011, 03:27 AM #18
bonbonbon
dead babies in a tree
Originally posted by River
well the way I set my login is wierd. I didn't use sessions at all and it was one of those ghetto login things.

anyway thanks for showing me stuff i didn't know. Smile

back to mw2 section >Smile


^=NOOB


L2c#
mw2 is dead like your websites login w/o ngu
10-20-2011, 11:29 PM #19
Pichu
RIP PICHU.
Originally posted by Epic
I already gave you the code/query, did I not?

Here's the query you need:
    
mysql_query("UPDATE $tbl_name SET password='$newpass' WHERE id=$_SESSION['id'] LIMIT 1");



As I also said previously, you first have to start the session (typically done in the first few lines of a script):
    
session_start();


But of course, at some point, you'll have to have to first have added the user's ID to the $_SESSION superglobal array; you would have done that in another script (mostly a script pertaining to the user logging in).

Since I now am aware that you are new to PHP, let me give you a breakdown of everything I pointed out earlier (and in this post):


Remember, session_start() starts a new "session" for each new person to visit your site. This session (also referred to as a "session cookie") is something like a cookie, except stored server side (and it disappears after the user closes his or her browser). You can, similar to a cookie, store information in a session. This can be used to pass information about a specific user from one script to another, this information is stored in the $_SESSION superglobal array. Note that you have to call session_start() at the beginning of each script (unless you're calling it in a script that's being included into another). You may want to read more about sessions here: You must login or register to view this content.

Knowing that, we can use sessions to store things like the user ID. We could do this in our log in script:
    
$query = mysql_query("SELECT user_id, username, password FROM users WHERE username='$username'"); // get the data
$result = mysql_fetch_assoc($query); // fetch the array

// check for correct username and password
if ($username == $result['username'] && $password == $result['password'])
{
session_start(); // start the session
$_SESSION['username'] == $username; // store the username
$_SESSION['user_id'] == $result['user_id']; // store the user's ID
}


While the above script is greatly simplified and totally unsafe (so don't use it), you can easily see how we would set the user's ID.

This will then allow us to use the session information in another script, for example, your script (to change the password of the user), we'd call session_start() and then we'd be able to use all the session data in the query (specifically the user's ID).

If you're new to PHP, I'd highly encourage you to read up on it as much as you can, if you You must login or register to view this content. you'll be taken to a fantastic tutorial on PHP, if you read through that, you should be ready to write some scripts of your own. Also, be sure to gain some basic skills with HTML.

Here's some basic debugging tips:

Please practice properly indenting and styling your code. For example:
    
// This is BASad Awesome
if (isset($_COOKIE["mycookie"])) {
$count = 1;
} else {
$count = 0;
}

// This is GOOSad Awesome
if (isset($_COOKIE["mycookie"]))
{
$count = 1;
}
else
{
$count = 0;
}


It may seem odd, but it'll make your code easier to debug (and generally easier to understand and read), both for you and those trying to help you. Its true that there's no truly correct way, but there are ways to make it easier on people (and yourself).

Another tip I'd have is to make sure you allow for errors and warnings (and be sure its set strictly so you get all errors and warnings). When you get an error, do not continue, stop, and go back to your code (also, test your code very frequently, that way you don't amass a large amount of errors). Also, fix both errors and warnings. When you get an error, go to the line where its occurring, and check that line (as well as lines above and below it), if you don't understand the error, just Google it.


Lastly, a development tip, first create a full plan of your website.

Then create a full plan of your database. This "plan" is referred to as a schema, there's plenty of tutorials on how to draw these out (and plenty of visual tools to help you).

After that, you need to plan out your script: what you want it to do, the functions you'll need to create, the functions and constructs that PHP has to offer, and since PHP is primarily written in the procedural paradigm, try to write some pseudo-code to plan it all out.

And finally, write your script, you should know exactly what to write (based on the plan) allowing you to write the code efficiently and quickly. Also, debug your code as errors and warnings come, and be sure to reload the page/script often, that way you can pick up on errors and warnings early.

That will help to cut out confusion.



Just to come full circle, back to the problem at hand. If my explanation did not answer your question, you're going to have to explain your question more clearly.




EDIT/UPDATE:

Just read your update, not really sure if you're actually getting closer (in fact, you may be getting farther, read the first part of my post).


...Mutha F*ckin boss is all I have to say. You self taught or did you take classes?

The following 2 users say thank you to Pichu for this useful post:

Epic?,

Copyright © 2026, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo