Blogger Information
Blog 33
fans 0
comment 0
visits 25871
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP用户注册邮件激活账户的实现代码
非常缪
Original
490 people have browsed it

我们在注册一个网站的账户时,通常都会收到一封含点击链接激活的邮件,而它是怎么激活我们的账户的呢,今天向大家介绍一种方法。

预备条件

我们在注册账户时,一般在用户表中会记录下我们的id、用户名、密码、邮箱或手机号,还会有一个账户激活与否的字段。我们假设它为 activation varchar(50) 注册时一般都会生成一个激活码,并且把激活码插入activation字段,我们可以使用$activation_key=bin2hex(openssl_random_pseudo_bytes(16)); 来生成,并且把它插入字段。

在链接中保存激活信息

既然我们点击了邮件里的链接后,就激活了账户,那么说明这个链接里,必然储存了激活信息。而它应该储存哪些信息呢,首先,必须有激活码,还有用户注册时的邮箱或者id,我们这里用邮箱。例如下面这个链接。

复制代码 代码如下:


$message.="<a href="." rel="external nofollow" http://www.XXXXX.com/activate.php?email=".urlencode($email)."&key=$activation_key".">Activate</a>";

$email使我们注册时的邮箱,我们用urlencode()来编码一下,将字符串用于 URL 的请求部分,$activation_key就是我们生成的激活码了,我们用服务器向这个email发送激活邮件,而这个在邮箱客户端里,会显示成一个超链接,提示你点击,点击后,我们就把email和key传送到了activate.php文件,也就是开始执行验证并激活账户了。

在activate.php中验证信息

我们使用URL请求向activate.php传入用户邮箱和激活码,现在只需要调取数据库中原有的信息进行对比,就可以验证用户了,所以我们第一步才将激活码插入用户表中,我写了一个activate.php的例子:

<?php

$link=mysqli_connect("localhost", "root", "root", "project") or die("Database Access Denied");//连接数据库

if (!isset($_GET['email'])||!isset($_GET["key"])){

 echo "<div class='alert alert-danger'>Account Activation Failed</div>";

 exit;//如果邮件链接损坏,没有传入用户激活信息,则不执行后续步骤

}

$email=$_GET['email'];

$key=$_GET['key'];

$email=mysqli_real_escape_string($link, $email);

$key=mysqli_real_escape_string($link, $key);//转义特殊字符

$sql="UPDATE users SET activation='activated' WHERE (user_email='$email' AND activation='$key') LIMIT 1";

$result=mysqli_query($link, $sql);//查询email与key匹配的数据项,并且更新activation字段到activated

if (mysqli_affected_rows($link)==1){

 echo "<div>Account Activated</div>";

 echo '<a href="index.php" rel="external nofollow" type="button">Login</a>';

 echo "<br/>";

}else{

 echo "<div>Account Activation Failed Or Already Activated</div>";

}

?>

现在账户就激活了,用户在登录时,先匹配一下activation是否为activated,接着再进行后续步骤


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!