How do i make a token expire

Viewed 13823

I'm trying to code a password recovery script with PHP, and after having a look around here in SO, the consensus for best practice seems to be

  • Generate Token with expiry
  • Send token via email to user
  • User clicks on token and changes password.

I currently have functions to generate a token, but how would i go about making it expire?Also, what would be a good shelf-life for the token?

Token Generation code:

    function crypto_rand_secure($min, $max) {
        $range = $max - $min;
        if ($range < 0) return $min; // not so random...
        $log = log($range, 2);
        $bytes = (int) ($log / 8) + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd >= $range);
        return $min + $rnd;
}

function GenerateToken($length){
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
    $codeAlphabet.= "0123456789";
    for($i=0;$i<$length;$i++){
        $token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))];
    }
    return $token;
}

P.s the code above was copy-pasted from another question here on S.O

4 Answers

Fetch the input email form my db. Generate and store a token with length 10 mixed with 0123456789qwertzuioplkjhgfdsayxcvbnm in my db. Send Email with the params and UPDATE users SET token to expire after 5 min.

**   <?php
    if (isset($_POST["forgotPass"])) {
        $connection = new mysqli("localhost", "root", "", "");

        $email = $connection->real_escape_string($_POST["email"]);

        $data = $connection->query("SELECT id FROM users WHERE email='$email'");

        if ($data->num_rows > 0) {
            $string = "0123456789qwertzuioplkjhgfdsayxcvbnm";
            $string = str_shuffle($string);
            $string = substr($string, 0, 10);
            $url = "resetPassword.php?token=$string&email=$email";

            mail($email, "Reset password", "To reset your password, please visit this: $url", "From: me@domain.com\r\n");

            $connection->query("UPDATE users SET token='$string', expire = DATE_ADD(NOW(), INTERVAL 5 MINUTE) WHERE email='$email'");

            echo "Please check your email!";
        } else {
            echo "Please check your inputs!";
        }
    }
?>
<html>
    <body>
        <form action="forgotPassword.php" method="post">
            <input type="text" name="email" placeholder="Email"><br>
            <input type="submit" name="forgotPass" value="Request Password">
        </form>
    </body>
</html>                           

**

Related