Jump to content
Larry Ullman's Book Forums

Chapter 18 - forgot_password.php

Recommended Posts

So I have everything up and running and I have modified the login app to my personal needs.  That being said, it  seems that the conditional that requires the password_hash() function only has a solution created from the variable that creates a random string, leaving the password_hash() function with only one parameter, the $p variable:

    if ($uid) { // If everything's OK.

        // Create a new, random password:
        $p = substr(md5(uniqid(rand(), true)), 3, 15);
        $ph = password_hash($p);

        // Update the database:
        $q = "UPDATE users SET pass='$ph' WHERE user_id=$uid LIMIT 1";
        $r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br>MySQL Error: " . mysqli_error($dbc));

        if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.

            // Send an email:
            $body = "Your password to log into <whatever site> has been temporarily changed to '$p'. Please log in using this password and this email address. Then you may change your password to something more familiar.";
            mail($_POST['email'], 'Your temporary password.', $body, 'From: admin@sitename.com');

            // Print a message and wrap up:
            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>';
            include('../../../PHP and MySQL - For Dynamic Sites - 5th/ch18/html/includes/footer.html');
            exit(); // Stop the script.

        } else { // If it did not run OK.
            echo '<p class="error">Your password could not be changed due to a system error. We apologize for any inconvenience.</p>';

    } else { // Failed the validation test.
        echo '<p class="error">Please try again.</p>';


} // End of the main Submit conditional.


This created the following email error message to be delivered:

An error occured in script 'C:\xampp\htdocs\LocalServer\larry_ullman_php\login_ex\forgot_password.php' on line 45:  password_hash() expects at least 2 parameters, 1 given
 Date/Time:9-4-18 09:29:14

The temporary password email is mailed as is should, the problem being that because the password_hash() function created an error the random string isn't stored in the database and the password column is wiped clean,  leaving no further option for logging in with the new password.  I have begun searching for a solution using multiple queries and the list() function but the code example is apparently flawed and as is will never function properly.

Link to comment
Share on other sites


  • Create New...