I am wanting to use a html form to reset passwords to a hashed md5 password. I will include all of my code. i get a blank screen when i submit the form. I am a beginner so please keep that in mind. I check myphpadmin and the hashed password does not change.
<html>
<head><title> Administrator reset password page</title></head>
<body>
<form action="forgotpass.php" method="post">
<table>
<tr><td>User Name:</td><td><input type="text" name="password" /></td></tr>
<tr><td>Password:</td><td><input type="text" name="user" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Reset Password"/></td> </tr>
</table>
</form>
</body>
</html>
<?php
include "connect.php"
$tmpPass = $_POST['password'];
$tmpuser= $_POST['user'];
$tmpPass = md5($tmpPass);
$sql = mysql_query("UPDATE employee set pass = $tmpPass WHERE usr = $tmpuser");
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) {
echo 'Password Has Been Reset Successfully';
/*
$email_message.= "Hello ";
$email_message.= "User with username: " .$tmpUser. "\n";
$email_message.= "Your New password: " .$_POST['password']. "\n";
$email_to = "registration#joshuamoorehead.com";
$email_subject = "Registration";
*/
else {
echo 'Error: '. $conn->error;
}
$conn->close();
?>
You're missing quotes around your string values:
$sql = mysql_query("UPDATE employee set pass = '$tmpPass' WHERE usr = '$tmpuser'");
Also, why are you running your query a second time?
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) { // <-- HERE
echo 'Password Has Been Reset Successfully';
Your $sql variable will contain the boolean result of your query, you need to check that variable is true as opposed to running the query again:
if($sql === true) {
echo 'Password Has Been Reset Successfully';
Related
I've been having this weird bug, basically what happens is that I have this App on Android and whenever I try to add a new "user" one of it's values (Called "Contacto") sometimes is wrong, the weird part is that it happens in a completely random way, here is my .php
<?PHP
$con=mysqli_connect("localhost","root","","proyecto");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['txtNombre']) && isset($_POST['txtcontactousuarionuevo']) &&
isset($_POST['txtPass']) && isset($_POST['txtprograma'])){
$nombreestudiante = $_POST['txtNombre'];
$contactoestudiante = $_POST['txtcontactousuarionuevo'];
$passestudiante = $_POST['txtPass'];
$programa = $_POST['txtprograma'];
$query = "INSERT INTO estudiante(Nombre, Contacto, Id_Periodo_FK, Pass)
VALUES ('$nombreestudiante', $contactoestudiante, 4, '$passestudiante');";
$query .= "INSERT INTO estudiante_programa(EstudianteE_P_FK, ProgramaE_P_FK)
VALUES(LAST_INSERT_ID(), $programa)";
$result =mysqli_multi_query($con,$query);
if($result > 0){
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "success";
exit;
}
echo "Insert Successfully";
}
else{
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "failed";
exit;
}
echo "Something Error";
}
}
?>
<html>
<head><title>Insert | ProyectoBD</title></head>
<body>
<h1>Insert ProyectoBD| <a>Santiago Troitiño C - 201421697</a></h1>
<form action="<?PHP $_PHP_SELF ?>" method="post">
Nombre <input type="text" name="txtNombre" value=""/><br/>
Contacto <input type="text" name="txtcontactousuarionuevo" value=""/><br/>
Pass <input type="text" name="txtPass" value=""/><br/>
<input type="submit" name="btnSubmit" value="Insert"/>
</form>
</body>
My app has a Login Screen and a button that takes it to a register form, the .php executed on that page (Login page) looks like this:
<?PHP
include_once("connection.php");
if(isset($_POST['txtUsername']) && isset($_POST['txtPassword'])){
$username = $_POST['txtUsername'];
$password = $_POST['txtPassword'];
$query = "SELECT * FROM estudiante WHERE Nombre = '$username'
AND Pass = '$password'";
$result = mysqli_query($conn, $query);
if($result->num_rows > 0){ //has record. correct username and password
echo "success";
while($row = $result->fetch_assoc()) {
echo " ". $row["Id_Estudiante"]. "";
exit;
}
exit;
}
else{
echo "Wrong username and password";
exit;
}
exit;
}
?>
<html>
<head><title>Login | ProyectoBD</title></head>
<body>
<h1>Login ProyectoBD | <a>Santiago Troitiño C - 201421697</a></h1>
<form action="<?PHP $_PHP_SELF ?>" method="post">
Nombre <input type="text" name="txtUsername" value="" placeholder="Ingresar Nombre" /><br/>
Password <input type="password" name="txtPassword" value="" placeholder="Ingresar Pass" /><br/>
<input type="submit" name="btnSubmit" value="Login"/>
</form>
</body>
</html>
Those are the only .php excuted on this part of the app...As you can see on this image the number "2147483647" keeps appearing at complete random times,
I used that number for a register once but kkeps appearing
Any ideas of how may I solve this? Thanks!
What is the data type of Contacto in your database? Does the issue present itself when you include Non-Numeric characters. For example, if you have your data type in your database for a phone number as a numeric type (BIGINT, INT) and your users attempt to enter VARCHAR characters like hyphens i.e. "111-111-1111" it can cause the database to save the entry as the highest number the data type can hold. If this issue occurs when you use non-numeric characters, change your data type for Contacto to VARCHAR.
I am making php login function and I have come across a problem. In one part of the script I am testing whether all of the info is inserted in html form that is fed to the script via $_POST variable. And in one part, the script correctly evaluates whether only username is not entered or only password, and it correctly evaluates whether password is wrong BUT when I enter correct user/pass, it activates error "Username and password not entered". I can't figure it out. Is it possible that FLASE && FALSE equals TRUE?
---Edit----
Ok, I see now that I should included all of the relevant files in this question. So here they are:
index.php
<?php
session_start();
if (isset($_SESSION['login_message'])) {
$message = $_SESSION['login_message'];
unset($_SESSION['login_message']);
}
?>
<html>
<head>
<?php
require_once("include/head.php");
?>
</head>
<body>
<form action="auth/login.php" method="post">
<table>
<tr>
<td>
<img src="graphics/znak_hrz.png" alt="Znak HRZ" style="height: 200px; padding: 10px;">
</td>
<td>
<table style="padding: 10px;">
<tr>
<td><?php if (isset($message)) {echo "<td>" . $message . "</td>";}?></td>
</tr>
<tr>
<td>
<label for="username">Username:</label>
<input id="username" type="text" name="username" />
</td>
</tr>
<tr>
<td>
<label for="password">Password:</label>
<input id="password" type="password" name="password" />
</td>
</tr>
<tr>
<td style="text-align: center;">
<input type="submit" name="login" value="Login" />
</td>
</tr>
</table>
</td>
<td>
<img src="graphics/znak_eskadrile.png" alt="Znak eskadrile" style="height: 200px; padding: 10px;">
</td>
</tr>
</table>
</form>
</body>
</html>
login.php
<?php
session_start();
// This script will deny access if following conditions are met in that order:
// - Username not entered
// - Password not entered
// - Username and password not entered
// - User doesn't exist in the database
// - User is deactivated in the database
// - The password is wrong
// Upon successful login, it will redirect user to secure/index.php and
// upon unsuccessful login it will return him to index.php for another try.
// If username is not set, set an error message
if (empty($_POST['username']) && !empty($_POST['password'])) {
$_SESSION['login_message'] = "Username missing";
}
// If password is not set, set an error message
if (empty($_POST['password']) && !empty($_POST['username'])) {
$_SESSION['login_message'] = "Password missing.";
}
//If username AND password are not set, set an error message
if (empty($_POST['username']) && empty($_POST['password'])) {
$_SESSION['login_message'] = "Username and password empty.";
}
// Check if the username exists in the database and if the password is correct
if (!isset($_SESSION['login_message']) && !empty($_POST['username']) && !empty($_POST['password'])) {
require_once("database.php");
// Sanitize incoming username and password
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
// Determine whether an account exists matching this username and password
$stmt = $auth_db->prepare("SELECT uid, pid, password, access_category, last_log, active FROM " . TBL_USERS . " WHERE username = ?");
// Bind the input parameters to the prepared statement
$stmt->bind_param('s', $username);
// Execute the query
$stmt->execute();
// Assign results of query to temporary variables
$stmt->bind_result($uid, $pid, $db_password, $access_category, $last_log, $active);
$stmt->fetch();
// If user doesn't exist in the database, deny login
if (!isset($uid)) {
$_SESSION['login_message'] = "User doesn't exist.";
}
// If user is deactivated, deny login
if (isset($uid) && !$active) {
$_SESSION['login_message'] = "User is deactivated.";
}
// If the password is wrong, deny login
if (isset($uid) && $active && $db_password != md5($password)) {
$_SESSION['login_message'] = "Wrong password.";
}
if (!isset($_SESSION['login_message'])) {
// Close previous statement
$stmt->close();
// Update the account's last_login column
$stmt = $auth_db->prepare("UPDATE " . TBL_USERS . " SET last_log = NOW() WHERE username = ?");
var_dump($stmt);
$stmt->bind_param('s', $username);
$stmt->execute();
// Set session variable
$_SESSION['username'] = $username;
$_SESSION['uid'] = $uid;
$_SESSION['pid'] = $pid;
$_SESSION['last_log'] = $last_log;
$_SESSION['active'] = $active;
$_SESSION['access_category'] = $access_category;
}
}
if (!isset($_SESSION['login_message'])) {
header('Location: ../secure/index.php');
} else if (isset($_SESSION['login_message'])) {
header('Location: ../index.php');
}
?>
secure/index.php
<?php
session_start();
require_once("../auth/login.php");
?>
<html>
<head>
<?php
#if($_SESSION['access_category'] == '0') {
# header('Location: eth93sl/');
#}
?>
</head>
<body>
<?php
echo "uid:" . $_SESSION['uid'] . "<BR>";
echo "username: " . $_SESSION['username'] . "<BR>";
echo "active: " . $_SESSION['active'] . "<BR>";
echo "last_log: " . $_SESSION['last_log'] . "<BR>";
echo "access_category: " . $_SESSION['access_category'] . "<BR>";
?>
</body>
</html>
The problem was that the login.php script was executing twice because of the line three in secure/index.php, a remnant line from another login system I was experimenting with. And second time that the script got called, it had no $_POST data, hence no username and no password so the apropriate conditional got activated.
Reminded me that when I come across a problem, it is always good to broaden my view to other files as well.
My class is attempting to make our own game.. But, we can't get the submit page to send to the database in PhpMyAdmin. When you click submit, it sends blank entries to the database, like if you hadn't filled in any of the blanks. Can someone help with this problem. Thanks!!
My index.php page.
<html>
<head>
<meta charset="UTF-8">
<title> Register New Account </title>
<link rel="stylesheet" type="text/css" href="td.css">
</head>
<body>
<?php
/* $count=$count+1;
echo " count " . $count; */
if($_POST['submit_id'] == 1)
{
/* echo "testing"; */
if($_POST['Username'] == NULL)
{
$message = 'Please enter your Username.';
}
if($_POST['Email'] == NULL)
{
$message = 'Please enter your Email.';
}
if($_POST['Confirm'] == NULL)
{
$message = 'Please re-enter your Email.';
}
if($_POST['Password'] == NULL)
{
$message = 'Please enter your Password.';
}
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "******", "Tower_Defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
$TableList = " `Username`, `Password`, `Email`, `Confirm` ";
$Values = " '$Username', '$Password', '$Email', '$Confirm' ";
if($message != NULL)
{
echo "$message";
}
?>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <br />
Username: <input type="text" name="Username" id= "Username"> <br />
Email: <input type = "text" name = "Email" id= "Email"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm"> <br />
Password: <input type = "password" name = "Password" id = "Password"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Check if Available!" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
My insert.php page
<html>
<body>
<?php
$Username = $_POST['name'];
$con=mysqli_connect("localhost", "root", "******", "Tower_Defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
UPDATE:
I added in the changes that someone had suggested in moving the checks to insert.php and now the email and confirm email check does not work. Can anyone help?
index.php
<html>
<body>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "insert.php" method = "post"> <br />
Username: <input type="text" name="Username" id= "Username" required = "1"> <br />
Email: <input type = "text" name = "Email" id= "Email" required = "1"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm" required = "1"> <br />
Password: <input type = "password" name = "Password" id = "Password" required = "1"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Reset Page" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
insert.php
<html>
<body>
<?php
if($_POST['submit_id'] == 1)
{
echo "testing";
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "abc123", "tower_defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
}
}
if($message != NULL)
{
echo "$message";
}
$con=mysqli_connect("localhost", "root", "abc123", "tower_defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
</html>
I see two main problems here -
First, the action of your form points to itself. That means that the $_POST array submits to index.php, and your insert.php page has no access to that information. Index.php runs through the validation checks, and if everything checks out, it assigns the $_POST values to variables and quits. That's where the data dies. There is no method for getting the information over to the file insert.php. So if you manually open the file insert.php in a browser, the $_POST array will be empty, and it will simply insert blanks.
There are several ways to resolve this. The simplest, most expeditious way would be the single page solution - move the insert.php code into the index.php file inside that last else block.
else {
//echo "next date <br>";
// create account
$Username = $_POST['name'];
//etc.. code to insert data from insert.php
Another solution would be to move all the validation code to insert.php, display any form errors on that page, and make the user go back a page if validation fails. In that case, you would change the action of the form to insert.php:
<form action="insert.php" method="post">
This approach is less user-friendly, and not an ideal solution. Really a better practice is to use Javascript for form validation and PHP for form processing. That may be outside the scope of your class...
Second, this code is wide open to SQL injection. Instead of putting variables directly into your SQL statements, you need to use parameterized queries. Take a look at this SO question about how to parameterize queries with mysqli.
The mistakes that I found:
First things first your code submits the values received from the form to index.php itself so there is no question of values getting insert at the first place because the insert query is not run.
In index.php check the query to SELECT email and username. The variables do not have any value when the query is run because the values get transferred couple of lines AFTER the queries (at the lines where you have $email = $_POST['Email']). Moreover you have missed the $ sign in the query related to email.
Coming to insert.php you have missed quotes in the global variable $_POST[] in the insert query viz. $_POST['email'].
Check for these errors and let me know if it works.
I have a table and one of the field is TempPass which is blank for all users. When user requests to change the password, instead of updating their existing password, my script adds the temporary password which is emailed to the user, to the TempPass field using SHA. The following line shows the change:
$query = "UPDATE users SET TempPass=SHA('$p') WHERE UserID=$uid";
I save the password during registration using the following line:
$password = md5(mysql_real_escape_string($_POST['password']));
The following if my HTML file:
<?php include "config.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="theStylesScripts/lostPassStyle.css" type="text/css" media="all" />
<title>Reset Password</title>
</head>
<body>
<?php
include("mailerClass/class.phpmailer.php");
include("mailerClass/class.smtp.php");
if (isset($_POST['submitted'])) { // Handle the form.
if (empty($_POST['email'])) { // Validate the email address.
$uid = FALSE;
echo '<p><font color="red" size="+1">You forgot to enter your email address!</font></p>';
}
if (empty($_POST['temppass'])) { // Validate the email address.
$uid = FALSE;
echo '<p><font color="red" size="+1">You forgot to enter your temporary password!</font></p>';
}
if (empty($_POST['newpass'])) { // Validate the email address.
$uid = FALSE;
echo '<p><font color="red" size="+1">You forgot to enter your new password!</font></p>';
}
else {
// Check for the existence of that email address.
$query = "SELECT UserID FROM users WHERE EmailAddress='". mysql_real_escape_string($_POST['email']) . "'";
$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
if (mysql_num_rows($result) == 1) {
// Retrieve the user ID.
list($uid) = mysql_fetch_array ($result, MYSQL_NUM);
}
else {
echo '<p><font color="red" size="+1">The submitted email address does not match those on file!</font></p>';
$uid = FALSE;
}
}
if ($uid) { // If everything’s OK.
// Make the query.
$query = "THIS IS THE QUERY THAT WILL COMPARE THE USEREMAIL WITH THE TEMPORARY PASSWORD ASSIGNED AND EMAILED TO WHAT THE USER ENTERED IN THE FORM";
$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
if ("USEREMAIL WITH THE AUTO ASSIGNED TEMPORARY PASSWORD MATCHES WITH THE TEMPORARY PASSWORD ENTERED BY THE USER") { // If it ran OK.
$query = "THIS IS THE QUERY THAT WILL UPDATE THE EXISTING PASSWORD WITH THE NEW PASSWORD ENTERED BY USER";
$query = "SET TEMPPASS BACK TO NULL FOR THAT USERID";
echo '<h3>Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the "Change Password" link.</h3>';
mysql_close(); // Close the database connection.
//include (‘./includes/footer.html’); // Include the HTML footer.
exit();
} else { // If it did not run OK.
echo '<p><font color="red" size="+1">Your password could not be changed due to a system error. We apologize for any inconvenience.</font></p>';
}
}
else { // Failed the validation test.
echo '<p><font color="red" size="+1">Please try again.</font></p>';
}
} // End of the main Submit conditional.
?>
<h1>Reset Your Password</h1>
<p>Enter your email address below and your password will be reset.</p>
<form action="resetPass.php" method="post">
<fieldset>
<p><b>Email Address:</b> <input type="email" name="email" size="20" maxlength="40" value="" /></p>
<p><b>Temporary Password:</b> <input type="text" name="temppass" size="20" maxlength="40" value="" /></p>
<p><b>New Password:</b> <input type="text" name="newpass" size="20" maxlength="40" value="" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Create New Password" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
</div>
</body>
</html>
How do I modify the following codes to achieve what I am looking to do:
if ($uid) { // If everything’s OK.
// Make the query.
$query = "THIS IS THE QUERY THAT WILL COMPARE THE USEREMAIL WITH THE TEMPORARY PASSWORD ASSIGNED AND EMAILED TO WHAT THE USER ENTERED IN THE FORM";
$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
if ("USEREMAIL WITH THE AUTO ASSIGNED TEMPORARY PASSWORD MATCHES WITH THE TEMPORARY PASSWORD ENTERED BY THE USER") { // If it ran OK.
$query = "THIS IS THE QUERY THAT WILL UPDATE THE EXISTING PASSWORD WITH THE NEW PASSWORD ENTERED BY USER";
$query = "SET TEMPPASS BACK TO NULL FOR THAT USERID";
echo 'password changed';
mysql_close(); // Close the database connection.
exit();
} else { // If it did not run OK.
echo 'no change. error';
}
}
Also, should I save the new password in md5 format?
Please note: I will be updating to mysqli soon.
if ($uid) { // If everything’s OK.
// Make the query.
$query = "SELECT * FROM users WHERE EmailAddress='".mysql_real_escape_string($_POST['email'])."' AND TempPass='".mysql_real_escape_string($_POST['temppass'])."'";
$result = mysql_query ($query) or trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error());
if (mysql_row_count($result)==1) { // If it ran OK.
$query = "UPDATE users SET password=SHA2('".mysql_real_escape_string($_POST['newpass'])."',512) WHERE EmailAddress='".mysql_real_escape_string($_POST['email'])."'";
$query = "UPDATE users SET TempPass='' WHERE EmailAddress='".mysql_real_escape_string($_POST['email'])."'";
echo 'password changed';
mysql_close(); // Close the database connection.
exit();
} else { // If it did not run OK.
echo 'no change. error';
}
}
It's not secure to store new passwords in MD5, because it has been cracked, use some other hashing like SHA512.
I have a page title changepassword.php ... In this page, users are able to change their password for an account. The query goes through and gives the message that it sent, however, the database does not change. The password stays the same as it used to be. I am using a sha1 hash that I am not used to (first time using it). Anyone know what is happening with it? Thanks!
<?php
session_start ();
$user_name = $_SESSION['user_name'];
if($user_name)
{
//user is logged in
if(isset($_POST['submit']))
{
//check fields
$oldpassword = $_POST['oldpassword'];
$newpassword = $_POST['newpassword'];
$repeatnewpassword = $_POST['repeatnewpassword'];
//check password against db
$connect=mysql_connect("localhost","root","passssssssword") or die();
mysql_select_db("database") or die();
$queryget= mysql_query ("SELECT user_pass FROM users WHERE user_name='$user_name'") or die("Query didn't work.");
$row = mysql_fetch_assoc ($queryget);
$oldpassworddb = $row['user_pass'];
//check passwords
if (sha1($oldpassword)==$oldpassworddb)
{
if ($newpassword==$repeatnewpassword)
{
if (strlen ($newpassword)>25 || strlen ($newpassword)<6)
{
echo "Password must be between 6 and 25 characters";
}
else
{
//change password in db
$newpassword = sha1($newpassword);
$querychange = mysql_query("UPDATE users SET password='$newpassword' WHERE user_name='$user_name'");
session_destroy();
die ("Your password has been changed. <a href='index.php'>Return</a> to the main page and login with your new password.");
}
}
else
die ("New passwords do not match!");
}
else
die ("Old password is inncorrect!");
}
else
{
echo
"<form action = 'changepassword.php' method = 'POST'>
<table>
<tr>
<td>
Old password:
</td>
<td>
<input type='text' name='oldpassword'><p>
</td>
</tr>
<tr>
<td>
New password:
</td>
<td>
<input type='password' name='newpassword'>
</td>
</tr>
<tr>
<td>
Repeat new password:
</td>
<td>
<input type='password' name='repeatnewpassword'>
</td>
</tr>
<table>
<input type='submit' name='submit' value='Change password'>
</form>
";
}
}
else
die("You must be logged in to change your password!");
?>
Query_1:
SELECT user_pass FROM users WHERE user_name='$user_name'
Your Query_2:
UPDATE users SET **password**='$newpassword' WHERE user_name='$user_name'
But, Query_2 should be:
UPDATE users SET **user_pass**='$newpassword' WHERE user_name='$user_name'
Not sure if literal/single quotes will allow PHP to interpolate the variables. I usually use sprintf, too. Also, in general you don't want to just check on username, but username AND old password.
"SELECT user_pass FROM users WHERE user_name='$user_name'"
should be:
$sql = sprintf("select user_pass from users where user_name = "%s",$user_name);
also, your "die()" would be better if you output the mysql_error(), i.e.
$connect=mysql_connect("localhost","root","passssssssword") or die();
mysql_select_db("database") or die("cannot connect".mysql_error());
But, probably the fastest way to troubleshoot is to put an error on the mysql_query:
$sql = sprintf("UPDATE users SET password="%s" WHERE user_name="%s"",$newpassword,$user_name);
$querychange = mysql_error($sql) or die ("Error updating: ".mysql_error());