Search code examples
phpmysqlwebforgot-password

PHP managing forgot password


I'm working on a forgot password page and trying to figure out the best way to do it. Currently, when a user goes to the page it asks for their email. The script checks if the account exists, and sends them an email with a link to click to reset their password.

The link contains a token (which is just md5(uniqid())) and the email address to match to the database when the user chooses a new password. It stores the token in a database table password_resets along with an expiration date of 24hrs from now and a foreign key to their account details.

When the user chooses a new password it matches the token to the password_resets table, the email to that foreign key's email address, and makes sure the expiration date is in the future before setting the new password and deleting the record from password_resets.

Is this an efficient way of doing it? It almost seems redundant to have a whole table for this purpose. Is there a better way to do it?


Solution

  • Usually i would recommend the same method but i noticed that you wrote on an efficient way for the same. There can be one actually.I am using the following library

    <?php
        # $key is super secret
        $key = "someRandomKey";
        function gen_token($email,$username) {
            $token = array(
                "email" => $email,
                "username" => $username,
                "created" => time()
            );
            return JWT::encode($token, $key);
        }
    
        function validate_token($token,$newPassword) {
            # Step below only works on valid token generates on your server
            $data = (array) JWT::decode($jwt, $key, array('HS256'));
            $currentTime = time();
            # Validate difference between $currentTime and $data["created"]
            # If time valid update password
        }
    ?>
    

    This method would reduce database latency considerably and also gives you the option to store some validation data on token itself.