php实现邮箱激活功能

php实现邮箱激活功能

一、样例

二、文件结构

其中swiftmailer-master是第三方插件,用来发验证邮件

三、核心代码

doAction.php 响应页面

  1 <?php
  2 header("content-type:text/html;charset=utf-8;");
  3 require_once 'config/config.php';
  4 require_once 'functions/common.func.php';
  5 require_once 'functions/mysql.func.php';
  6 require_once 'swiftmailer-master/lib/swift_required.php';
  7 $link = connect3();//数据库的连接
  8 $table = "51zxw_user";//表名字
  9 $act = $_REQUEST['act'];
 10 $username = $_REQUEST['username'];
 11 $password = md5($_REQUEST['password']);
 12 
 13 switch ($act){
 14     case 'reg':
 15 //         echo  '注册成功!';
 16         //关闭事物的自动提交
 17         mysqli_autocommit($link, false);
 18         //得到当前时间
 19         $regTime = time(); 
 20         //得到邮箱
 21         $email = $_POST['email'];
 22         //生成一个token
 23         $token = md5($username.$password.$regTime);
 24         //生成一个token的过期时间
 25         $token_exptime = $regTime+24*3600;//表示一天以后过期
 26         //插入数据
 27         $data = compact('username','password','email','regTime','token','token_exptime');
 28         $res = insert($link, $data, $table);
 29         //调用第三方的库发送邮件
 30         //创建一个transport对象,确定发送到哪个邮箱
 31         $transport = Swift_SmtpTransport::newInstance("smtp.sina.com",25);
 32         //账号名
 33         $transport->setUsername('clivelyn@sina.com');
 34         //密码
 35         $transport->setPassword('lin123');
 36         //创建一个发送邮箱的对象
 37         $mailer = Swift_Mailer::newInstance($transport);
 38         //发送邮件要有发送人,要有标题,要有邮件主体
 39         //发送邮件信息对象
 40         $message = Swift_Message::newInstance();
 41         //谁来发送
 42         $message->setFormat(array('clivelyn@sina.com'));
 43         //发送到哪里,谁注册,我发送到谁那里
 44         $message->setTo($email);
 45         //设置主题
 46         $message->setSubject('注册账号激活邮箱');
 47         //邮件中的链接
 48         $activeStr = "?act=active&username={$username}&token={$token}";
 49         $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$activeStr;
 50         //设置邮件的正文内容
 51         //链接已经成功,url再加密
 52         $urlEncode = urlencode($url);
 53 //         echo $urlEncode;
 54         $emailBody = <<<EOF
 55                               欢迎{$username}使用账号激活功能,请点击连接激活账号:
 56                 <a href="{$url} target="_blank">{$urlEncode}</a><br/>
 57             (该链接在24小时内有效) 如果上面不是链接形式,请将地址复制到您的浏览器(例如IE)的地址栏再访问。
 58         
 59 EOF;
 60         
 61         //真正的发送
 62         $message->setBody($emailBody,'text/html','utf-8');
 63         try {
 64             $res1 = $mailer->send($message);
 65             if($res && $res1){
 66                 mysqli_commit($link);
 67                 mysqli_autocommit($link,true);
 68                 alertMes("注册信息,请激活使用", "index.php");
 69             }
 70         }catch (Swift_ConnectionException $e){
 71             //echo $e;
 72             die('邮件服务器错误:').$e->getMessage();
 73         }
 74         
 75         
 76         
 77         
 78         break;
 79     case 'active'://激活功能
 80 //         echo  '激活成功!';
 81         $token = $_GET['token'];
 82         //因为要进行转义
 83         $username = mysqli_real_escape_string($link, $username);
 84         //sql语句
 85         $query = "select id,token_exptime from {$table} where username='{$username}'";
 86         //mysqli的查询语句
 87         $user = fetchOne($link, $query);
 88         if($user){
 89             $now = time();
 90             $token_exptime = $user['token_exptime'];
 91             //判断是否激活过期
 92             if($now>$token_exptime){//过期
 93                 delete($link, $table,"username={$username}");
 94                 alertMes("激活码过期,请重新注册", "index.php");
 95             }else{//激活,把status改为1就好
 96                 $data = array('status'=>1);
 97                 $res = update($link, $data, $table);
 98                 if($res){//激活成功
 99                     alertMes("激活成功", "index.php");
100                 }else{
101                     alertMes("激活失败,请重新激活", "index.php");
102                 }
103             }
104         }else{
105             alertMes("激活失败,没有找到要激活的用户", 'index.php');
106         }
107         break;
108 }
109 echo "<br/>你好";

工具函数

mysql.fun.php  封装的mysqli的工具

  1 <?php
  2 /**
  3  * 连接
  4  * @param string $host
  5  * @param string $user
  6  * @param string $password
  7  * @param string $charset
  8  * @param string $database
  9  * @return object 连接标识符
 10  */
 11 function connect1($host,$user,$password,$charset,$database) {
 12     $link = mysqli_connect ( $host, $user, $password ) or die ( '数据库连接失败<br/>ERROR ' . mysqli_connect_errno () . ':' . mysqli_connect_error () );
 13     mysqli_set_charset ( $link, $charset );
 14     mysqli_select_db ( $link, $database ) or die ( '指定数据库打开失败<br/>ERROR ' . mysqli_errno ( $link ) . ':' . mysqli_error ( $link ) );
 15     return $link;
 16 }
 17 /**
 18  * 连接 需要传递数组
 19  * @param array $config
 20  * @return object
 21  */
 22 function connect2($config) {
 23     $link = mysqli_connect ( $config ['host'], $config ['user'], $config ['password'] ) or die ( '数据库连接失败<br/>ERROR ' . mysqli_connect_errno () . ':' . mysqli_connect_error () );
 24     mysqli_set_charset ( $link, $config ['charset'] );
 25     mysqli_select_db ( $link, $config ['dbName'] ) or die ( '指定数据库打开失败<br/>ERROR ' . mysqli_errno ( $link ) . ':' . mysqli_error ( $link ) );
 26     return $link;
 27 }
 28 /**
 29  * 用常量的形式建立连接
 30  * @return unknown
 31  */
 32 function connect3(){
 33     $link = mysqli_connect ( DB_HOST, DB_USER, DB_PWD ) or die ( '数据库连接失败<br/>ERROR ' . mysqli_connect_errno () . ':' . mysqli_connect_error () );
 34     mysqli_set_charset ( $link, DB_CHARSET );
 35     mysqli_select_db ( $link, DB_DBNAME ) or die ( '指定数据库打开失败<br/>ERROR ' . mysqli_errno ( $link ) . ':' . mysqli_error ( $link ) );
 36     return $link;
 37 }
 38 
 39 /*
 40  array(
 41  'username'=>'king',
 42  'password'=>'king',
 43  'age'=>'12',
 44  'regTime'=>'123123123'
 45  );
 46  INSERT user(username,password,age,regTime) VALUES('king','king','12','123123123');
 47  */
 48 /**
 49  * 插入操作
 50  * @param object $link
 51  * @param array $data
 52  * @param string $table
 53  * @return boolean
 54  */
 55 function insert($link,$data,$table){
 56     $keys = join ( ',', array_keys ( $data ) );
 57     $vals = "'" . join ( "','", array_values ( $data ) ) . "'";
 58     $query = "INSERT {$table}({$keys}) VALUES({$vals})";
 59     $res = mysqli_query ( $link, $query );
 60     if ($res) {
 61         return mysqli_insert_id ( $link );
 62     } else {
 63         return false;
 64     }
 65 }
 66 
 67 /*
 68  array(
 69          'username'=>'king123',
 70          'password'=>'king123',
 71          'age'=>'32',
 72          'regTime'=>'123123123'
 73  );
 74  UPDATE user SET username='king123',password='king123',age='32',regTime='123123123' WHERE id=1
 75 */
 76 /**
 77  * 更新操作
 78  * @param object $link
 79  * @param array $data
 80  * @param string $table
 81  * @param string $where
 82  * @return boolean
 83  */
 84 function update($link, $data, $table, $where = null) {
 85     foreach ( $data as $key => $val ) {
 86         $set .= "{$key}='{$val}',";
 87     }
 88     $set = trim ( $set, ',' );
 89     $where = $where == null ? '' : ' WHERE ' . $where;
 90     $query = "UPDATE {$table} SET {$set} {$where}";
 91     $res = mysqli_query ( $link, $query );
 92     if ($res) {
 93         return mysqli_affected_rows ( $link );
 94     } else {
 95         return false;
 96     }
 97 }
 98 
 99 //DELETE FROM user WHERE id=
100 /**
101  * 删除操作
102  * @param object $link
103  * @param string $table
104  * @param string $where
105  * @return boolean
106  */
107 function delete($link, $table, $where = null) {
108     $where = $where ? ' WHERE ' . $where : '';
109     $query = "DELETE FROM {$table} {$where}";
110     $res = mysqli_query ( $link, $query );
111     if ($res) {
112         return mysqli_affected_rows ( $link );
113     } else {
114         return false;
115     }
116 }
117 
118 /**
119  * 查询指定记录
120  * @param object $link
121  * @param string $query
122  * @param string $result_type
123  * @return array|boolean
124  */
125 function fetchOne($link, $query, $result_type = MYSQLI_ASSOC) {
126     $result = mysqli_query ( $link, $query );
127     if ($result && mysqli_num_rows ( $result ) > 0) {
128         $row = mysqli_fetch_array ( $result, $result_type );
129         return $row;
130     } else {
131         return false;
132     }
133 }
134 
135 /**
136  * 查询所有记录
137  * @param object $link
138  * @param string $query
139  * @param string $result_type
140  * @return array|boolean
141  */
142 function fetchAll($link, $query, $result_type = MYSQLI_ASSOC) {
143     $result = mysqli_query ( $link, $query );
144     if ($result && mysqli_num_rows ( $result ) > 0) {
145         while ( $row = mysqli_fetch_array ( $result, $result_type ) ) {
146             $rows [] = $row;
147         }
148         return $rows;
149     } else {
150         return false;
151     }
152 }
153 
154 /**
155  * 得到表中的记录数
156  * @param object $link
157  * @param string $table
158  * @return number|boolean
159  */
160 function getTotalRows($link, $table) {
161     $query = "SELECT COUNT(*) AS totalRows FROM {$table}";
162     $result = mysqli_query ( $link, $query );
163     if ($result && mysqli_num_rows ( $result ) == 1) {
164         $row = mysqli_fetch_assoc ( $result );
165         return $row ['totalRows'];
166     } else {
167         return false;
168     }
169 }
170 
171 /**
172  * 得到结果集的记录条数
173  * @param object $link
174  * @param string $query
175  * @return boolean
176  */
177 function getResultRows($link, $query) {
178     $result = mysqli_query ( $link, $query );
179     if ($result) {
180         return mysqli_num_rows ( $result );
181     } else {
182         return false;
183     }
184 }
185 
186 
187 
188 /**
189  * @param object $link
190  */
191 function getServerInfo($link) {
192     return mysqli_get_server_info ( $link );
193 }
194 /**
195  * @param object $link
196  */
197 function getClientInfo($link) {
198     return mysqli_get_client_info ( $link );
199 }
200 
201 /**
202  * @param object $link
203  */
204 function getHostInfo($link){
205     return mysqli_get_host_info($link);
206 }
207 
208 /**
209  * @param object $link
210  */
211 function getProtoInfo($link) {
212     return mysqli_get_proto_info ( $link );
213 }

跳转工具

common.func.php 激活成功之后的跳转

 1 <?php
 2 /**
 3  * 弹出提示信息并且跳转
 4  * @param string $mes
 5  * @param string $url
 6  */
 7 function alertMes($mes,$url){
 8     echo "<script>
 9             alert('{$mes}');
10             location.href='{$url}';
11     </script>";
12     die;
13 }

四、完整代码

完整代码我会放在GitHub上面

链接如下:

原文地址:https://www.cnblogs.com/Renyi-Fan/p/8550764.html