Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Using PHP, what are some ways to generate a random confirmation code that can be stored in a DB and be used for email confirmation? I can't for the life of me think of a way to generate a unique number that can be generated from a user's profile. That way I can use a function to make the number small enough to be included in the URL (see this link). Remember, the user has to click on the link to "confirm/activate" his/her account. If I can't use numbers, I have no problems using both letters and numbers.

With that said, I've tried hashing the username along with a "salt" to generate the random code. I know there has to be a better way, so let's hear it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
284 views
Welcome To Ask or Share your Answers For Others

1 Answer

$random_hash = md5(uniqid(rand(), true));

That will be 32 alphanumeric characters long and unique. If you want it to be shorter just use substr():

$random_hash = substr(md5(uniqid(rand(), true)), 16, 16); // 16 characters long

Alternative methods to generate random data include:

$random_hash = md5(openssl_random_pseudo_bytes(32));
$random_hash = md5(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));

// New in PHP7
$random_hash = bin2hex(random_bytes(32));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...