Change and Confirm Password MySql PHP

so I have a page where the users can change the password, but I want to have it more secure, by asking the user the old password and then a new one, I just have no idea how to validate that can anyone help me please? Here's my actual code:

    <?php
//Inicio de uma session que autentica e valida o login feito em login.php
  session_start(); 
  //Redirecionar um Admin ou um SuperAdmin para a devida página com as devidas permissões! 
include '../functions/redirect.php';
 isAuthenticated();
 $user = $_SESSION['users']['username'];

?>
<!DOCTYPE html>
<?php

    require '../functions/database.php';

    if ( !empty($_POST)) {
        // Manter a validação dos erros
        $usernameError = null;
        $passwordError = null;

        $password = $_POST['password'];
        // $confirm_password = null;
        // $new_password = null;

        // Validar os inputs
        $valid = true;

          if (empty($password)) {
            $passwordError = 'Introduza a password!';
            $valid = false;
        }

        // Inserir os dados
     if ($valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $password = password_hash($password, PASSWORD_BCRYPT);
            $sql = "UPDATE users SET password = ? WHERE username = '$user'";
            $q = $pdo->prepare($sql); 
            $q->execute(array($password)); 
            header("Location: index.php");
            Database::disconnect();
    }

 }

?>

I am assuming you have an "old_password" and a "new_password" field in your form that the user fills in. You first check the old password entered against the hashed password already in your users table.

NOTE the use of filter sanitizing the information entered in your form before passing it through to an SQL query.

If all is good then you go ahead and test the new password entered however you want. If the new password is validated then you go ahead and update your users table.

// Connect to database
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$valid = false;
if ( !empty($_POST)) {
    // Manter a validação dos erros
    $usernameError = null;
    $passwordError = null;

    // Read in old password from form field
    $old_password = filter_var($_POST['old_password'], FILTER_SANITIZE_STRING);

    // Validar os inputs
    if (empty($old_password)) {
        $passwordError = 'Introduza a password!';
        $valid = false;
    }

    // Check old password
    else {
        // Read in old password from db            
        // build SELECT statement with variable
        $sql = 'SELECT password FROM users WHERE username = :USER';
        $sql->bindValue(':USER', $user);
        $sql->execute();

        if ($sql->rowCount() > 0) {
            // Read in value from select
            $row = $sql->fetchObject();
            $user_password = $row->password;

            // Test entered password against hashed current user password
            if (password_verify($old_password, $user_password)) {
                $valid = true;
            }

            else {
                // passwords do not match
                $valid = false
            }
        }
        else {
            // Did not find user in table
            $valid = false;
        }
    }
}

// Inserir os dados
 if ($valid) {
    // Test new password
    $new_password = filter_var($_POST['new_password'], FILTER_SANITIZE_STRING);

    // here you would test length, or content or whatever ...

    // if still valid you save the new password
    $new_password = password_hash($new_password, PASSWORD_BCRYPT);
    $sql = "UPDATE users SET password = :NEWPASSWORD WHERE username = :USER';
    $sql->bindValue(':NEWPASSWORD', $new_password);
    $sql->bindValue(':USER', $user);
    $sql->execute();

    // header("Location: index.php");
}

Database::disconnect();

I am working on a section of code that changes a password in a database upon completion of the following form: &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/h

I would also point out that $valid = true after $_POST submit makes no sense because you are making $valid true by sending a $_POST where it takes any input no matter what it is as long as something is there and for a password update you actually need all of the data. Then later you check additional requirements and then change $valid to false.

You should start with $valid = false and when requirements are met you can return it as True.

Also to add to Derek's answer I suggest that you make additional small check to make sure user has to check new password twice to avoid situation where they make a mistake and later can't log in due to that.

In this tutorial I will explain how user can change their old password.First Create a html form with three fields. Old Password; New Password; Confirm Password; Now Validate these fields with javascript. After this create a php script for change password . PHP script given below : HTML code for Change Password Form

To do this you have to process in 2 times :

In a first time you have to get the current password of the user. To verify his id :

$password = $_POST['password'];
if (password_verify($password, $remote->password))
   // the password is right

-> remote is the result of sql request

Then, in a second time, you will compare the new password and the confirmation of this password. If those are the same :

$new = $_POST['new_password'];
$confirm = $_POST['confirm'];
if ($new == $confirm)
   $new = password_hash($new, PASSWORD_BCRYPT);
   // execute your sql insertion

Please excuse my english

Change MySQL user password using UPDATE statement The first way to change the password is to use the UPDATE statement to update the user table of the mysql database. After executing the UPDATE statement, you also need to execute the FLUSH PRIVILEGES statement to reload privileges from the grant table in the mysql database.

One very important feature of any good membership website is a password reset system because some users are bound to forget their password. In this tutorial, I outline the steps involved in recovering a user's password; we will also be implementing such a system using PHP and a MySQL database in this tutorial.

Verifies that the given hash matches the given password. Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it.

How to Create a Secure PHP Login System with Registration that uses password_hash(), MySQL with PDO, jQuery for AJAX Forms and Bootstrap Templates.Over time PHP has been adding features that promote the development of secure applications, as well deprecated or removed features that made it easy to write insecure code.

Comments
  • Where exactly are you stuck? If you want to check the old password before updating, just fetch the user by their username and verify the password? It's just like a login.
  • There are two issues with your code though. 1. You're not setting the $user variable anywhere. 2. You're using parameterized prepared statements for the password (which is good) but you should really use it for the username as well. The username is probably even more dangerous since that isn't hashed.
  • @MagnusEriksson at the top of the page I have the $user defined $user = $_SESSION['users']['username'];
  • You should show us all the relevant code (so we know what all the variables contain and that you simply haven't missed defining any or have typos). Anyway, if you read my two previous comments, you should be able to make some attempts.
  • I've updated my question
  • It is not necessary to escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.
  • Although I agree with @JayBlanchard that escaping passwords may create unnecessary additional coding it definitely does not change the password as I have used this throughout numerous sites and PHP scripts. But, I maintain, I agree that it is unnecessary for passwords that will be hashed before being sent to the SQL query.
  • Thanks for your awnser, actually I have just one password field on the database
  • @Carlos there is only one password field in the database in my answer/example. However there should be at least 2 password fields in your form (1/old and 2/new) and I agree with Chris that you should actually have 3 password fields on the form (1/old, 2/new and 3/confirm new) forcing the user to type the new password in twice, correctly, before it being sent to the database.
  • @DerekErb - "it definitely does not change the password" ...of course it does. That's sole purpose of escaping/sanitizing strings are to change them. Take the string: <hello></hello>. Sanitizing that string that would change it to: `` (empty string). So, escaping or sanitizing strings should not be used. Imagine someone having a password: <foo>password</foo>. If you sanitize it, it will become password, which we all can agree would be one of the worse passwords you can have. You've effectively made the users password way more unsecure.