生成确认码以进行电子邮件确认 [英] Generating confirmation code for an email confirmation

查看:88
本文介绍了生成确认码以进行电子邮件确认的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PHP,有什么方法可以生成可以存储在数据库中并用于电子邮件确认的随机确认代码?我一辈子都想不出一种可以从用户个人资料中生成唯一编号的方法.这样,我可以使用一个函数来使数字足够小以包含在URL中(参见链接).请记住,用户必须单击链接以确认/激活"他/她的帐户.如果我不能使用数字,那么使用字母和数字都不会有问题.

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.

推荐答案

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

这将是32个字母数字字符,并且是唯一的.如果您希望它更短些,请使用substr():

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));

这篇关于生成确认码以进行电子邮件确认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆