Home  >  Article  >  Backend Development  >  PHP user registration email verification and activation account example_PHP tutorial

PHP user registration email verification and activation account example_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:48:461244browse

Nowadays, most websites require users to register by email, and then send an account activation email to the user's registered email. The user can activate the account by clicking on the link. Let me introduce the specific method below.

Functional requirements

PHP program development. Users register on the website and need to activate their account through an email link. After the user registers (user information is written to the database), if the user does not log in to the email to activate the account, it is stipulated that user information without activated account will be automatically deleted after 24 hours. , after the activation link expires, users can also use this information to register on the website

Prepare data sheet

The field Email in the user information table is very important. It can be used to verify users, retrieve passwords, and even for website parties, it can be used to collect user information for email marketing. The following is the table structure of the user information table t_user:

The code is as follows Copy code
 代码如下 复制代码

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;

CREATE TABLE IF NOT EXISTS `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL COMMENT 'username',
`password` varchar(32) NOT NULL COMMENT 'password',
`email` varchar(30) NOT NULL COMMENT 'email',
`token` varchar(50) NOT NULL COMMENT 'Account activation code',
`token_exptime` int(10) NOT NULL COMMENT 'Activation code validity period',
`status` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Status, 0-not activated, 1-activated',
`regtime` int(10) NOT NULL COMMENT 'Registration time',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

HTML

Place a registration form on the page, and users can enter registration information, including username, password and email.
 代码如下 复制代码


   

用户名:


   

密 码:


   

E-mail:


   


The code is as follows Copy code

Username:


Password:


E-mail:



Necessary front-end verification is required for user input. Regarding the form verification function, it is recommended that you refer to the article on this site: An example explains the application of the form verification plug-in Validation. This article skips the front-end verification code. In addition, there should be There is an input box that requires the user to re-enter the password, so I just skipped it because I was lazy.
register.php

The user submits the registration information to register.php for processing. register.php needs to complete two major functions: writing data and sending emails.

First of all, it contains the two necessary files, connect.php and smtp.class.php. These two files are included in the download package provided outside. You are welcome to download.

The code is as follows Copy code
 代码如下 复制代码


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;
}

include_once("connect.php");//Connect to the database

include_once("smtp.class.php");//Email sending class
 代码如下 复制代码

$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);

Then we need to filter the information submitted by the user and verify whether the username exists (the front end can also verify). $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 'The username already exists, please change it to another username'; exit; }
Then we encrypt the user password and construct the activation identification code:
The code is as follows Copy code
$password = md5(trim($_POST['password'])); //Encrypt password $email = trim($_POST['email']); //Email $regtime = time(); $token = md5($username.$password.$regtime); //Create an activation code $token_exptime = time()+60*60*24;//The expiration time is 24 hours later $sql = "insert into `t_user` (`username`,`password`,`email`,`token`,`token_exptime`,`regtime`) values ​​('$username','$password','$email','$token','$token_exptime','$regtime')"; mysql_query($sql);

In the above code, $token is the constructed activation identification code, which is composed of user name, password and current time and is encrypted by md5. $token_exptime is used to set the expiration time of the activation link URL. The user can activate the account within this time period. In this example, the activation is valid within 24 hours. Finally, these fields are inserted into the data table t_user.

When the data is inserted successfully, call the email sending class to send the activation information to the user's registered mailbox. Pay attention to forming the constructed activation identification code into a complete URL as the activation link when the user clicks. The following is the detailed code:

The code is as follows Copy code
 代码如下 复制代码

if(mysql_insert_id()){
    $smtpserver = ""; //SMTP服务器,如:smtp.163.com
    $smtpserverport = 25; //SMTP服务器端口,一般为25
    $smtpusermail = ""; //SMTP服务器的用户邮箱,如xxx@163.com
    $smtpuser = ""; //SMTP服务器的用户帐号xxx@163.com
    $smtppass = ""; //SMTP服务器的用户密码
    $smtp = new Smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); //实例化邮件类
    $emailtype = "HTML"; //信件类型,文本:text;网页:HTML
    $smtpemailto = $email; //接收邮件方,本例为注册用户的Email
    $smtpemailfrom = $smtpusermail; //发送邮件方,如xxx@163.com
    $emailsubject = "用户帐号激活";//邮件标题
    //邮件主体内容
    $emailbody = "亲爱的".$username.":
感谢您在我站注册了新帐号。
请点击链接激活您的帐号。

    '_blank'>/demo/register/active.php?verify=".$token."

    如果以上链接无法点击,请将它复制到你的浏览器地址栏中进入访问,该链接24小时内有效。";
    //发送邮件
    $rs = $smtp->sendmail($smtpemailto, $smtpemailfrom, $emailsubject, $emailbody, $emailtype);
    if($rs==1){
        $msg = '恭喜您,注册成功!
请登录到您的邮箱及时激活您的帐号!';    
    }else{
        $msg = $rs;    
    }
}
echo $msg;

if(mysql_insert_id()){
$smtpserver = ""; //SMTP server, such as: smtp.163.com
$smtpserverport = 25; //SMTP server port, usually 25
$smtpusermail = ""; //The user's email address of the SMTP server, such as xxx@163.com
$smtpuser = ""; //SMTP server user account xxx@163.com
$smtppass = ""; //User password of SMTP server
$smtp = new Smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); //Instantiate mail class
$emailtype = "HTML"; //Email type, text: text; web page: HTML
$smtpemailto = $email; //Receive the email, in this case the email of the registered user
$smtpemailfrom = $smtpusermail; //Sending email party, such as xxx@163.com
$emailsubject = "User Account Activation";//Email Subject
//Email body content
$emailbody = "Dear".$username.":
Thank you for registering a new account on our site.
Please click the link to activate your account.
'_blank'>/demo/register/active.php?verify=".$token."

If the above link cannot be clicked, please copy it to your browser address bar to access it. The link will be valid for 24 hours. ";
//Send email
$rs = $smtp->sendmail($smtpemailto, $smtpemailfrom, $emailsubject, $emailbody, $emailtype);
If($rs==1){
​​​​$msg = 'Congratulations, your registration is successful!
Please log in to your email to activate your account in time! '; 
}else{
         $msg = $rs;                                                }  
}
echo $msg;

There is also a very easy-to-use and powerful email sending class to share with everyone: use PHPMailer to send emails with attachments and support HTML content. You can use it directly.
active.php

If nothing goes wrong, the email you filled in when registering your account will receive an email from helloweba. At this time, you can directly click the activation link and let active.php handle it.

active.php receives the submitted link information and obtains the value of the parameter verify, which is the activation identification code. Query and compare it with the user information in the data table. If there is a corresponding data set, determine whether it has expired. If it is within the validity period, set the status field in the corresponding user table to 1, which means it has been activated. This completes the activation function. .

The code is as follows Copy code
 代码如下 复制代码

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;

include_once("connect.php");//Connect to the database $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 = 'Your activation period has expired, please log in to your account and resend the activation email.'; }else{ Mysql_query("update t_user set status=1 where id=".$row['id']); If(mysql_affected_rows($link)!=1) die(0); ​​​​$msg = 'Activation successful! '; } }else{ $msg = 'error.'; } echo $msg;

After successful activation, you find that the token field is no longer useful and you can clear it. Next, we will explain the function for users to retrieve passwords, and also use email verification, so stay tuned.

Finally attach the email smtp.class.php to send the class

The code is as follows Copy code

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;

/* Contractor */

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 . [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数据库连接类

 代码如下
 代码如下 复制代码

$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); //北京时间
?>

复制代码
$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); //北京时间<🎜> ?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632757.htmlTechArticleMost websites now require users to register using their email address, and then send an account activation email to the user’s registered email address. Click the link to activate your account. Let me introduce the tools...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn