来源:http://blog.hao909.com/%E5%A6%82%E4%BD%95%E7%94%A8php%E7%BC%96%E5%86%99%E6%B3%A8%E5%86%8C%E5%90%8Eemail%E6%BF%80%E6%B4%BB%E7%9A%84%E9%AA%8C%E8%AF%81%E4%BB%A3%E7%A0%81/
通过使用Email验证激活的方法,可以有效的帮你阻止恶意的Spam和注册机器人的访问。
用php编写注册后Email验证激活的步骤非常简单,相信几分钟之内你就能学会。
总共需两个页面,register.php 和 verify.php
1. 用户注册表格 register.php
03 |
<form action="register.php" method="post" name="register"> |
04 |
用户名:<input type="text" name="username" /> |
05 |
密码:<input type="password" name="password" /> |
06 |
电子邮件:<input type="text" name="email" /> |
07 |
<input type="submit" value="注册" /> |
2. 创建用户数据表格 Users
01 |
CREATE TABLE IF NOT EXISTS `users` ( |
02 |
`id` int(11) NOT NULL auto_increment, |
03 |
`status` varchar(20) NOT NULL, |
04 |
`username` varchar(20) NOT NULL, |
05 |
`password` varchar(20) NOT NULL, |
06 |
`email` varchar(20) NOT NULL, |
07 |
`activationkey` varchar(100) NOT NULL, |
09 |
UNIQUE KEY `username` (`username`), |
10 |
UNIQUE KEY `email` (`email`), |
11 |
UNIQUE KEY `activationkey` (`activationkey`) |
12 |
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ; |
3. 创建验证码 用户注册信息存入数据表
我们使用状态‘verify’ 来表示尚未激活的用户。
1 |
$activationKey = mt_rand() . mt_rand() . mt_rand() . mt_rand() . mt_rand(); |
3 |
$username = mysql_real_escape_string($_POST[username]); |
4 |
$password = mysql_real_escape_string($_POST[password]); |
6 |
$email = mysql_real_escape_string($_POST[email]); |
8 |
$sql="INSERT INTO users (username, password, email, activationkey, status) VALUES ('$username', '$password', '$email', '$activationKey', 'verify')"; |
4. 发送验证码
01 |
echo "An email has been sent to $_POST[email] with an activation key. Please check your mail to complete registration."; |
03 |
##Send activation Email |
06 |
$subject = " YOURWEBSITE.com Registration"; |
07 |
$message = "Welcome to our website!\r\rYou, or someone using your email address, has completed registration at YOURWEBSITE.com. You can complete registration by clicking the following link:\rhttp://www.YOURWEBSITE.com/verify.php?$activationKey\r\rIf this is an error, ignore this email and you will be removed from our mailing list.\r\rRegards,\ YOURWEBSITE.com Team"; |
09 |
$headers = 'From: noreply@ YOURWEBSITE.com' . "\r\n" . |
11 |
'Reply-To: noreply@ YOURWEBSITE.com' . "\r\n" . |
13 |
'X-Mailer: PHP/' . phpversion(); |
15 |
mail($to, $subject, $message, $headers); |
5. 验证激活代码 verify.php
如果验证码相同,则激活用户。
01 |
$queryString = $_SERVER['QUERY_STRING']; |
03 |
$query = "SELECT * FROM users"; |
04 |
$result = mysql_query($query) or die(mysql_error()); |
06 |
while($row = mysql_fetch_array($result)){ |
08 |
if ($queryString == $row["activationkey"]){ |
09 |
echo "Congratulations!" . $row["username"] . " is now the proud new owner of a YOURWEBSITE.com account."; |
10 |
$sql="UPDATE users SET activationkey = '', status='activated' WHERE (id = $row[id])"; |
12 |
if (!mysql_query($sql)) { |
13 |
die('Error: ' . mysql_error()); |
16 |
// 到这里,用户已经完全激活了账号,你可以将页面跳转到登陆后的界面了 |