在做网站的时候。很多网站都有注册完会员就会给发邮箱连接进行认证。系统会自动向用户的邮箱发送一封邮件,这封邮件的内容就是一个URL链接,用户需要点击打开这个链接才能激活之前在该网站注册的帐号。激活成功后才能正常使用会员功能。
本文将结合实例,讲解如何使用PHP+Mysql完成注册帐号、发送激活邮件、验证激活帐号、处理URL链接过期的功能。
1、用户提交注册信息。
2、写入数据库,此时帐号状态未激活。
3、将用户名密码或其他标识字符加密构造成激活识别码(你也可以叫激活码)。
4、将构造好的激活识别码组成URL发送到用户提交的邮箱。
5、用户登录邮箱并点击URL,进行激活。
6、验证激活识别码,如果正确则激活帐号。
用户信息表中字段Email很重要,它可以用来验证用户、找回密码、甚至对网站方来说可以用来收集用户信息进行Email营销,以下是用户信息表t_user的表结构:
CREATE TABLE IF NOT EXISTS `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL COMMENT '用户名',
`password` varchar(32) NOT NULL COMMENT '密码',
`email` varchar(30) NOT NULL COMMENT '邮箱',
`token` varchar(50) NOT NULL COMMENT '帐号激活码',
`token_exptime` int(10) NOT NULL COMMENT '激活码有效期',
`status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '状态,0-未激活,1-已激活',
`regtime` int(10) NOT NULL COMMENT '注册时间',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
新建的register.php
<?php
include_once("connect.php"); //连接数据库
$username=stripslashes(trim($_POST['username']));
$query=mysql_query("select id from t_user where username='$username'");
$num=mysql_num_rows($query);
if($num==1){
echo '<script>alert("用户名已经存在的啦");window.history.go(-1);</script>';
exit;
}
$password=md5(trim($_POST['password']));
$email=trim($_POST['email']);
$regtime=time();
$token=md5($username.$password.$regtime); //创建用于识别激活码
$token_exptime=time()+60*60*24; //过期时间是24小时
$sql = "insert into `t_user` (`username`,`password`,`email`,`token`,`token_exptime`,`regtime`) values ('$username','$password','$email','$token','$token_exptime','$regtime')";
mysql_query($sql);
if(mysql_insert_id()){ //写入成功发送邮件
include_once("smtp.class.php");
$smtpserver = "smtp.qq.com"; //SMTP服务器
$smtpserverport = 25; //SMTP服务器端口
$smtpusermail = ""; //SMTP服务器的用户邮箱
$smtpuser = ""; //SMTP服务器的用户帐号
$smtppass = ""; //SMTP服务器的用户密码
$smtp=new Smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); //这里面的一个true是表示使用身份验证,否则不使用身份验证.
$emailtype = "HTML"; //信件类型,文本:text;网页:HTML
$smtpemailto = $email;
$smtpemailfrom = $smtpusermail;
$emailsubject = "用户帐号激活";
$emailbody = "亲爱的".$username.":<br/>感谢您在我站注册了新帐号。<br/>请点击链接激活您的帐号。<br/><a href='localhost/active.php?verify=".$token."' target='_blank'>http://localhost/active.php?verify=".$token."</a><br/>如果以上链接无法点击,请将它复制到你的浏览器地址栏中进入访问,该链接24小时内有效。<br/>如果此次激活请求非你本人所发,请忽略本邮件。<br/><p style='text-align:right'>-------- 51mubanji.com 敬上</p>";
}
?>
新建的active.php
<?php
include_once("connect.php");
$verify = stripslashes(trim($_GET['verify']));
$nowtime = time();
$query = mysql_query("select id,token_exptime from t_user where status='0' and `token`='$verify'");
$row = mysql_fetch_array($query);
if($row){
if($nowtime>$row['token_exptime']){ //30min
$msg = '您的激活有效期已过,请登录您的帐号重新发送激活邮件.';
}else{
mysql_query("update t_user set status=1 where id=".$row['id']);
if(mysql_affected_rows($link)!=1) die(0);
$msg = '激活成功!';
}
}else{
$msg = 'error.';
}
echo $msg;
?>
新建的connect.php
<?php
$host="localhost";
$db_user="root";
$db_pass="root";
$db_name="yctz";
$timezone="Asia/Shanghai";
$link=mysql_connect($host,$db_user,$db_pass);
mysql_select_db($db_name,$link);
mysql_query("Set Names UTF8");
header("Content-Type: text/html; charset=utf-8");
date_default_timezone_set($timezone); //北京时间
?>
新建的:smtp.class.php
<?php
class Smtp{
/* Public Variables */
var $smtp_port;
var $time_out;
var $host_name;
var $log_file;
var $relay_host;
var $debug;
var $auth;
var $user;
var $pass;
/* Private Variables */
var $sock;
/* Constractor */
function smtp($relay_host = "", $smtp_port = 25, $auth = false, $user, $pass) {
$this->debug = false;
$this->smtp_port = $smtp_port;
$this->relay_host = $relay_host;
$this->time_out = 30; //is used in fsockopen()
$this->auth = $auth; //auth
$this->user = $user;
$this->pass = $pass;
$this->host_name = "localhost"; //is used in HELO command
$this->log_file = "";
$this->sock = false;
}
/* Main Function */
function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "") {
$mail_from = $this->get_address($this->strip_comment($from));
$body = ereg_replace("(^|(\r\n))(\.)", "\1.\3", $body);
$header .= "MIME-Version:1.0\r\n";
if ($mailtype == "HTML") {
$header .= "Content-Type:text/html\r\n";
}
$header .= "To: " . $to . "\r\n";
if ($cc != "") {
$header .= "Cc: " . $cc . "\r\n";
}
$header .= "From: $from<" . $from . ">\r\n";
$header .= "Subject: " . $subject . "\r\n";
$header .= $additional_headers;
$header .= "Date: " . date("r") . "\r\n";
$header .= "X-Mailer:By Redhat (PHP/" . phpversion() . ")\r\n";
list ($msec, $sec) = explode(" ", microtime());
$header .= "Message-ID: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $mail_from . ">\r\n";
$TO = explode(",", $this->strip_comment($to));
if ($cc != "") {
$TO = array_merge($TO, explode(",", $this->strip_comment($cc)));
}
if ($bcc != "") {
$TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
}
$sent = true;
foreach ($TO as $rcpt_to) {
$rcpt_to = $this->get_address($rcpt_to);
if (!$this->smtp_sockopen($rcpt_to)) {
$this->log_write("Error: Cannot send email to " . $rcpt_to . "\n");
$sent = false;
continue;
}
if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
$this->log_write("E-mail has been sent to <" . $rcpt_to . ">\n");
} else {
$this->log_write("Error: Cannot send email to <" . $rcpt_to . ">\n");
$sent = false;
}
fclose($this->sock);
$this->log_write("Disconnected from remote host\n");
}
return $sent;
}
/* Private Functions */
function smtp_send($helo, $from, $to, $header, $body = "") {
if (!$this->smtp_putcmd("HELO", $helo)) {
return $this->smtp_error("sending HELO command");
}
// auth
if ($this->auth) {
if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
return $this->smtp_error("sending HELO command");
}
if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
return $this->smtp_error("sending HELO command");
}
}
if (!$this->smtp_putcmd("MAIL", "FROM:<" . $from . ">")) {
return $this->smtp_error("sending MAIL FROM command");
}
if (!$this->smtp_putcmd("RCPT", "TO:<" . $to . ">")) {
return $this->smtp_error("sending RCPT TO command");
}
if (!$this->smtp_putcmd("DATA")) {
return $this->smtp_error("sending DATA command");
}
if (!$this->smtp_message($header, $body)) {
return $this->smtp_error("sending message");
}
if (!$this->smtp_eom()) {
return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
}
if (!$this->smtp_putcmd("QUIT")) {
return $this->smtp_error("sending QUIT command");
}
return true;
}
function smtp_sockopen($address) {
if ($this->relay_host == "") {
return $this->smtp_sockopen_mx($address);
} else {
return $this->smtp_sockopen_relay();
}
}
function smtp_sockopen_relay() {
$this->log_write("Trying to " . $this->relay_host . ":" . $this->smtp_port . "\n");
$this->sock = @ fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Error: Cannot connenct to relay host " . $this->relay_host . "\n");
$this->log_write("Error: " . $errstr . " (" . $errno . ")\n");
return false;
}
$this->log_write("Connected to relay host " . $this->relay_host . "\n");
return true;
;
}
function smtp_sockopen_mx($address) {
$domain = ereg_replace("^.+@([^@]+)$", "\1", $address);
if (!@ getmxrr($domain, $MXHOSTS)) {
$this->log_write("Error: Cannot resolve MX \"" . $domain . "\"\n");
return false;
}
foreach ($MXHOSTS as $host) {
$this->log_write("Trying to " . $host . ":" . $this->smtp_port . "\n");
$this->sock = @ fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);
if (!($this->sock && $this->smtp_ok())) {
$this->log_write("Warning: Cannot connect to mx host " . $host . "\n");
$this->log_write("Error: " . $errstr . " (" . $errno . ")\n");
continue;
}
$this->log_write("Connected to mx host " . $host . "\n");
return true;
}
$this->log_write("Error: Cannot connect to any mx hosts (" . implode(", ", $MXHOSTS) . ")\n");
return false;
}
function smtp_message($header, $body) {
fputs($this->sock, $header . "\r\n" . $body);
$this->smtp_debug("> " . str_replace("\r\n", "\n" . "> ", $header . "\n> " . $body . "\n> "));
return true;
}
function smtp_eom() {
fputs($this->sock, "\r\n.\r\n");
$this->smtp_debug(". [EOM]\n");
return $this->smtp_ok();
}
function smtp_ok() {
$response = str_replace("\r\n", "", fgets($this->sock, 512));
$this->smtp_debug($response . "\n");
if (!ereg("^[23]", $response)) {
fputs($this->sock, "QUIT\r\n");
fgets($this->sock, 512);
$this->log_write("Error: Remote host returned \"" . $response . "\"\n");
return false;
}
return true;
}
function smtp_putcmd($cmd, $arg = "") {
if ($arg != "") {
if ($cmd == "")
$cmd = $arg;
else
$cmd = $cmd . " " . $arg;
}
fputs($this->sock, $cmd . "\r\n");
$this->smtp_debug("> " . $cmd . "\n");
return $this->smtp_ok();
}
function smtp_error($string) {
$this->log_write("Error: Error occurred while " . $string . ".\n");
return false;
}
function log_write($message) {
$this->smtp_debug($message);
if ($this->log_file == "") {
return true;
}
$message = date("M d H:i:s ") . get_current_user() . "[" . getmypid() . "]: " . $message;
if (!@ file_exists($this->log_file) || !($fp = @ fopen($this->log_file, "a"))) {
$this->smtp_debug("Warning: Cannot open log file \"" . $this->log_file . "\"\n");
return false;
;
}
flock($fp, LOCK_EX);
fputs($fp, $message);
fclose($fp);
return true;
}
function strip_comment($address) {
$comment = "\([^()]*\)";
while (ereg($comment, $address)) {
$address = ereg_replace($comment, "", $address);
}
return $address;
}
function get_address($address) {
$address = ereg_replace("([ \t\r\n])+", "", $address);
$address = ereg_replace("^.*<(.+)>.*$", "\1", $address);
return $address;
}
function smtp_debug($message) {
if ($this->debug) {
echo $message . "
;";
}
}
}
?>
最后yx.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>PHP用户注册邮箱验证激活帐号</title>
<style type="text/css">
.demo{width:400px; margin:40px auto 0 auto; min-height:250px;}
.demo p{line-height:30px; padding:4px}
.input{width:180px; height:20px; padding:1px; line-height:20px; border:1px solid #999}
.btn{position: relative;overflow: hidden;display:inline-block;*display:inline;padding:4px 20px 4px;font-size:14px;line-height:18px;*line-height:20px;color:#fff;text-align:center;vertical-align:middle;cursor:pointer;background-color:#5bb75b;border:1px solid #cccccc;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px; margin-left:48px}
</style>
<script type="text/javascript">
function chk_form(){
var user = document.getElementById("user");
if(user.value==""){
alert("用户名不能为空!");
return false;
//user.focus();
}
var pass = document.getElementById("pass");
if(pass.value==""){
alert("密码不能为空!");
return false;
//pass.focus();
}
var email = document.getElementById("email");
if(email.value==""){
alert("Email不能为空!");
return false;
//email.focus();
}
var preg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; //匹配Email
if(!preg.test(email.value)){
alert("Email格式错误!");
return false;
//email.focus();
}
}
</script>
</head>
<body>
<div id="main">
<h2 class="top_title">PHP用户注册邮箱验证激活帐号</h2>
<div class="demo">
<form id="reg" action="register.php" method="post" onSubmit="return chk_form();">
<p>用户名:<input type="text" class="input" name="username" id="user"></p>
<p>密 码:<input type="password" class="input" name="password" id="pass"></p>
<p>E-mail:<input type="text" class="input" name="email" id="email"></p>
<p><input type="submit" class="btn" value="提交注册"></p>
</form>
</div>
<br/>
</div>
</body>
</html>
关于本站 | 网站地图 | 手机版 | XML地图 | 反馈 | 版权申明 皖ICP备13006370号-1