現在大部份網站都需要用戶利用郵箱注冊,然後再發帳號激活郵件到用戶注冊郵箱,用戶點擊鏈接就可以激活帳號了,下面我來介紹一下具體方法。
功能需求
PHP程序開發,用戶在網站注冊,需要用戶通過郵件鏈接激活帳號,當用戶注冊後(用戶信息寫入數據庫),沒有登錄郵箱激活帳號,規定24小時後自動刪除沒有激活帳號的用戶信息,實現激活鏈接過期後,用戶還可以使用該信息在網站注冊
准備數據表
用戶信息表中字段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;
HTML
在頁面中放置一個注冊表單,用戶可以輸入注冊信息,包括用戶名、密碼和郵箱。
代碼如下 復制代碼<form id="reg" action="register.php" method="post">
<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>
對於用戶的輸入要進行必要的前端驗證,關於表單驗證功能,建議您參考本站文章:實例講解表單驗證插件Validation的應用,本文對前端驗證代碼略過,另外其實頁面中還應該有個要求用戶重復輸入密碼的輸入框,一時偷懶就此略過。
register.php
用戶將注冊信息提交到register.php進行處理。register.php需要完成寫入數據和發送郵件兩大功能。
首先包含必要的兩個文件,connect.php和smtp.class.php,這兩個文件在外面提供的下載包裡有,歡迎下載。
代碼如下 復制代碼
include_once("connect.php");//連接數據庫
include_once("smtp.class.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 '用戶名已存在,請換個其他的用戶名';
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);
上述代碼中,$token即構造好的激活識別碼,它是由用戶名、密碼和當前時間組成並md5加密得來的。$token_exptime用於設置激活鏈接URL的過期時間,用戶在這個時間段內可以激活帳號,本例設置的是24小時內激活有效。最後將這些字段插入到數據表t_user中。
當數據插入成功後,調用郵件發送類將激活信息發送給用戶注冊的郵箱,注意將構造好的激活識別碼組成一個完整的URL作為用戶點擊時的激活鏈接,以下是詳細代碼:
代碼如下 復制代碼if(mysql_insert_id()){
$smtpserver = ""; //SMTP服務器,如:smtp.163.com
$smtpserverport = 25; //SMTP服務器端口,一般為25
$smtpusermail = ""; //SMTP服務器的用戶郵箱,如[email protected]
$smtpuser = ""; //SMTP服務器的用戶帳號[email protected]
$smtppass = ""; //SMTP服務器的用戶密碼
$smtp = new Smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); //實例化郵件類
$emailtype = "HTML"; //信件類型,文本:text;網頁:HTML
$smtpemailto = $email; //接收郵件方,本例為注冊用戶的Email
$smtpemailfrom = $smtpusermail; //發送郵件方,如[email protected]
$emailsubject = "用戶帳號激活";//郵件標題
//郵件主體內容
$emailbody = "親愛的".$username.":<br/>感謝您在我站注冊了新帳號。<br/>請點擊鏈接激活您的帳號。<br/>
<a href='/demo/register/active.php?verify=".$token."' target=
'_blank'>/demo/register/active.php?verify=".$token."</a><br/>
如果以上鏈接無法點擊,請將它復制到你的浏覽器地址欄中進入訪問,該鏈接24小時內有效。";
//發送郵件
$rs = $smtp->sendmail($smtpemailto, $smtpemailfrom, $emailsubject, $emailbody, $emailtype);
if($rs==1){
$msg = '恭喜您,注冊成功!<br/>請登錄到您的郵箱及時激活您的帳號!';
}else{
$msg = $rs;
}
}
echo $msg;
還有一個相當好用且強大的郵件發送類分享個大家:使用PHPMailer發送帶附件並支持HTML內容的郵件,直接可以用哦。
active.php
如果不出意外,您注冊帳號時填寫的Email將收到一封helloweba發送的郵件,這個時候您直接點擊激活鏈接,交由active.php處理。
active.php接收提交的鏈接信息,獲取參數verify的值,即激活識別碼。將它與數據表中的用戶信息進行查詢對比,如果有相應的數據集,判斷是否過期,如果在有效期內則將對應的用戶表中字段status設置1,即已激活,這樣就完成了激活功能。
代碼如下 復制代碼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']){ //24hour
$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;
激活成功後,發現token字段並沒有用處了,您可以清空。接下來我們會講解用戶找回密碼的功能,也要用到郵箱驗證,敬請關注。
最後附上郵箱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("(^|(rn))(.)", "1.3", $body);
$header .= "MIME-Version:1.0rn";
if ($mailtype == "HTML") {
$header .= "Content-Type:text/htmlrn";
}
$header .= "To: " . $to . "rn";
if ($cc != "") {
$header .= "Cc: " . $cc . "rn";
}
$header .= "From: $from<" . $from . ">rn";
$header .= "Subject: " . $subject . "rn";
$header .= $additional_headers;
$header .= "Date: " . date("r") . "rn";
$header .= "X-Mailer:By Redhat (PHP/" . phpversion() . ")rn";
list ($msec, $sec) = explode(" ", microtime());
$header .= "Message-ID: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $mail_from . ">rn";
$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 hostn");
}
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 . "rn" . $body);
$this->smtp_debug("> " . str_replace("rn", "n" . "> ", $header . "n> " . $body . "n> "));
return true;
}
function smtp_eom() {
fputs($this->sock, "rn.rn");
$this->smtp_debug(". [EOM]n");
return $this->smtp_ok();
}
function smtp_ok() {
$response = str_replace("rn", "", fgets($this->sock, 512));
$this->smtp_debug($response . "n");
if (!ereg("^[23]", $response)) {
fputs($this->sock, "QUITrn");
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 . "rn");
$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("([ trn])+", "", $address);
$address = ereg_replace("^.*<(.+)>.*$", "1", $address);
return $address;
}
function smtp_debug($message) {
if ($this->debug) {
echo $message . "
;";
}
}
}
?>
connect數據庫連接類
代碼如下 復制代碼<?php
$host="localhost";
$db_user="";//用戶名
$db_pass="";//密碼
$db_name="demo";//數據庫
$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); //北京時間
?>