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
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
You can do this way
create a table called password_recovery with the following fields
Now while someone request for password recovery usually by entering login name or email get the iduser for that user. Then generate a token. You can set the expire_date as you want. Lets say its 1 day from now, you can use strtotime() to generate that. Insert these values in the password_recovery table.
Then send the email to the users email id something like
yourdomain.com/passrecover.php?h=[token from above]
Once user clicks on the link, run a code to check if the token is valid and if not expired . If so display the password reset form. You will have the iduser from that token. Else display the error message.
Finally once user reset the password , delete the row from the table.
You can in addition have a cronjob script to delete the expired tokens from the table.
To make it expire you need to store the creation date either on your system or somehow encoded in the token and check this when the token is redeemed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With