生成唯一的字符串为电子邮件激活链接PHP


Generating unique strings for email activation links PHP

我的问题有点棘手,找不到正确的方式来有效地表达它。我正在创建一个唯一的激活字符串/链接,在PHP中组合了哈希用户名和时间。然而,它获得要发送到数据库的数据的确切时间和将电子邮件激活链接发送到用户电子邮件帐户所需的实际时间是不同的(可能以毫秒为单位,有时以秒为单位)-这基本上意味着我的数据库和电子邮件帐户有不同的电子邮件激活链接。让我展示一个代码片段:

$username = $_POST[‘username’];
$table = ‘users’;
$activate_field = ‘activate’;
$activate_code = md5($_POST[‘username’]) +  time(); //provides unique code for activating
//few more lines of code then…
$query = $connect-> prepare(“INSERT INTO $table $acivate_field VALUES $activate_code”);
$query->execute();
//then the long code for sending the email with the activation code appended to the user’s email account

是否有一种更好的方法可以每秒生成唯一的字符串?谢谢你的时间,感谢任何帮助和/或建议。另外,我正在使用phpmailer发送电子邮件。

只需将生成的代码写入变量,然后将变量写入邮件和数据库因为我可以看到你已经有代码保存在变量之前,包括它在您的查询

另外,你不应该直接访问像$_POST这样的超全局变量,因为用户输入可能是恶意的出于同样的原因,你应该使用PDO准备语句,而不是字符串构建查询

mysql中的UUID()更好,但是php中的uniqid()带前缀也可以很好。

您可以将md5uniqidtime组合在一起,因此它在同一秒内也是唯一的。

$activate_code = md5(uniqid(time()));