PHP实现用户注册邮箱验证激活帐号
1、第一步打开编辑器新建一个HTML文件来写表单,代码如下:<!DOCTYPE HTML争犸禀淫><html><head><meta chars髫潋啜缅et="utf-8"><title>PHP用户注册邮箱验证激活帐号</title><style type="text/css">.demo {margin: 20px auto; width: 400px; border: 1px solid #ccc; line-height: 50px;text-align: center;}.input {width: 150px; height: 25px; border: 1px solid #ccc;}.btn {padding: 5px 15px; font-size: 16px; font-family: '微软雅黑'; background:#ff0066; color: #fff; border: none;}</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"> <div class="demo"> <form id="reg" action="register.php" method="post" onsubmit="return chk_form();"> 用户名:<input type="text" class="input" name="username" id="user"><br> 密 码:<input type="password" class="input" name="password" id="pass"><br> 邮 箱:<input type="text" class="input" name="email" id="email"><br> <input type="submit" class="btn" value="提交注册"> </form> </div> </div></body></html>

2、第二步建立数据库名为:user 的数据库 并建立一张用户表:用户表的SQL代码如下: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;


3、第三步新建一个connect.php文件用来设置数据库的链接和一些其他的设置,里面的代码如下:<?php$db_host="localhost"; //数据库主机$db_user="root"; //数据库用户名$db_pass="123456"; //数据库密码$db_name="user"; //选择的数据库$timezone="Asia/Shanghai"; //设置时区@$link=mysql_connect($db_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); //北京时间

4、第四步建立register.php用来处理用户提交过来的数据并进行存进数据库和发送邮件,具体代码如下:&造婷用痃lt;?phpinclude("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("smtp.class.php"); $MailServer = "smtp.qq.com"; //SMTP服务器 $MailPort = 25; //SMTP服务器端口 $smtpMail = "1223188688@qq.com"; //SMTP服务器的用户邮箱 $smtpuser = "1223188688@qq.com"; //SMTP服务器的用户帐号 $smtppass = "kzytvgyfgwgqhdah"; //SMTP服务器的用户密码 //创建$smtp对象 这里面的一个true是表示使用身份验证,否则不使用身份验证. $smtp = new Smtp($MailServer, $MailPort, $smtpuser, $smtppass, true); $smtp->debug = false; $mailType = "HTML"; //信件类型,文本:text;网页:HTML $email = $email; //收件人邮箱 $emailTitle = "百度经验用户帐号激活";//邮件主题 $emailBody = "亲爱的".$username.":<br/>感谢您在我站注册了新帐号。<br/>请点击链接激活您的帐号。<br/><a href='http://hacker.com/active.php?verify=".$token."' target='_blank'>http://hacker.com/active.php?verify=".$token."</a><br/>如果以上链接无法点击,请将它复制到你的浏览器地址栏中进入访问,该链接24小时内有效。<br/>如果此次激活请求非你本人所发,请忽略本邮件。<br/><p style='text-align:right'>-------- 百度经验 敬上</p>"; // sendmail方法 // 参数1是收件人邮箱 // 参数2是发件人邮箱 // 参数3是主题(标题) // 参数4是邮件主题(标题) // 参数4是邮件内容 参数是内容类型文本:text 网页:HTML $rs = $smtp->sendmail($email, $smtpMail, $emailTitle, $emailBody, $mailType); if($rs==true){ echo '<script>alert("恭喜您,注册成功!请登录到您的邮箱及时激活您的帐号!");window.history.go(-1);</script>'; }else{ echo "注册失败"; }}
5、第五步新建active.php来处理帐号的激活,具体代码如下:<?phpinclude("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;
6、smtp.class.php具体代码如下:<?phpclass smtp { /* Public Variables */ var $smtp_port; //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 __construct($relay_host = "", $smtp_port = 25, $user, $pass, $auth = false) { $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->host_name = "smtp.163.com"; //is used in HELO command $this->log_file = ""; $this->sock = FALSE; } /* Main Function */ function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "") { $header = ""; $mail_from = $this->get_address($this->strip_comment($from)); $body = mb_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 .= 'Content-type: text/html; charset=utf-8' . "\r\n"; } $header .= "To: " . $to . "\r\n"; if ($cc != "") { $header .= "Cc: " . $cc . "\r\n"; } $header .= "From: " . $from . "\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 (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"); } echo "<br>"; //echo $header; 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 (!mb_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 (mb_ereg($comment, $address)) { $address = mb_ereg_replace($comment, "", $address); } return $address; } function get_address($address) { $address = mb_ereg_replace("([ \t\r\n])+", "", $address); $address = mb_ereg_replace("^.*<(.+)>.*$", "\\1", $address); return $address; } function smtp_debug($message) { if ($this->debug) { echo $message . "<br>"; } } function get_attach_type($image_tag) // { $filedata = array(); $img_file_con = fopen($image_tag, "r"); unset($image_data); while ($tem_buffer = AddSlashes(fread($img_file_con, filesize($image_tag)))) $image_data .= $tem_buffer; fclose($img_file_con); $filedata['context'] = $image_data; $filedata['filename'] = basename($image_tag); $extension = substr($image_tag, strrpos($image_tag, "."), strlen($image_tag) - strrpos($image_tag, ".")); switch ($extension) { case ".gif": $filedata['type'] = "image/gif"; break; case ".gz": $filedata['type'] = "application/x-gzip"; break; case ".htm": $filedata['type'] = "text/html"; break; case ".html": $filedata['type'] = "text/html"; break; case ".jpg": $filedata['type'] = "image/jpeg"; break; case ".tar": $filedata['type'] = "application/x-tar"; break; case ".txt": $filedata['type'] = "text/plain"; break; case ".zip": $filedata['type'] = "application/zip"; break; default: $filedata['type'] = "application/octet-stream"; break; } return $filedata; }}
7、最后的效果截图如下:




