PHP User Registration Email Verification Activation Account Example _php tutorial

Source: Internet
Author: User
Tags ereg md5 encryption server port
Now most sites require users to use the mailbox registration, and then send the account activation email to the user registration mailbox, the user click on the link to activate the account, let me introduce the specific method.

Functional Requirements

PHP program development, users in the site registration, users need to activate the account through the mail link, when the user registration (user information to write to the database), no login mailbox activation account, 24 hours after the automatic deletion of the user information is not activated account, the activation chain after the period, the user can also use the information on the site registration

Preparing Data Sheets

User Information table field email is very important, it can be used to verify the user, retrieve the password, and even to the site can be used to collect user information for email marketing, the following is the User Information table T_user table structure:

copy code

CREATE TABLE IF not EXISTS ' t_user ' (
' id ' in T (one) NOT null auto_increment,
' username ' varchar (+) NOT null COMMENT ' user name ',
' password ' varchar (+) NOT NULL CO Mment ' password ',
' email ' varchar (+) NOT null COMMENT ' mailbox ',
' token ' varchar (NOT NULL COMMENT ' account Activation Code ',
' token _exptime ' int (ten) NOT null COMMENT ' activation code validity period ',
' status ' tinyint (1) NOT null DEFAULT ' 0 ' COMMENT ' state, 0-inactive, 1-activated ',
' Regtime ' int (ten) not NULL COMMENT ' registration time ',
PRIMARY KEY (' id ')
) Engine=myisam DEFAULT Charset=utf8;

Html

Place a registration form on the page where the user can enter the registration information, including the user name, password, and mailbox.

The code is as follows Copy Code

For the user's input to do the necessary front-end verification, about the form validation function, we recommend that you refer to this site article: Examples of the application of the form validation plugin validation, this article on the front-end verification code skipped, in fact, there should be a page that requires users to repeatedly enter the password input box, temporarily lazy to skip this.
register.php

The user submits the registration information to register.php for processing. Register.php needs to complete two functions of writing data and sending mail.

First contains the necessary two files, connect.php and smtp.class.php, these two files are included in the download package provided outside, welcome to download.

The code is as follows Copy Code


Include_once ("connect.php");//Connect database
Include_once ("smtp.class.php");//Mail Sending class

We then filter the information submitted by the user and verify that the user name exists (the front end can also be verified).

$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 ' username already exists, please change another user name ';
Exit
}

We then encrypt the user's password to construct the activation ID:

copy code

$password = MD5 (Trim ($_post[' password ')); /encryption password
$email = Trim ($_post[' email ');//mailbox
$regtime = time ();

$token = MD5 ($username. $password. $regtime);//create To activate identification code
$token _exptime = time () +60*60*24;//expires after 24 hours

$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, the $token is a constructed activation identification code, which is composed of the user name, password and the current time and MD5 encryption. $token _exptime is used to set the expiration time of the activation link URL, the user can activate the account during this time period, this example sets the activation valid within 24 hours. Finally, insert these fields into the data table T_user.

When the data is inserted successfully, the calling mail sending class sends the activation information to the user's registered mailbox, noting that the constructed activation identifier is composed of a full URL as the activation link when the user clicks, and the following is the detailed code:

The code is as follows Copy Code

If (mysql_insert_id ()) {
$smtpserver = ""; SMTP server, such as: smtp.163.com
$smtpserverport =;//smtp server port, typically
$smtpusermail = ""; The user mailbox of the SMTP server, such as xxx@163.com
$smtpuser = ""; The user account for the SMTP server xxx@163.com
$smtppass = ""; User password for SMTP server
$SMTP = new SMTP ($smtpserver, $smtpserverport, True, $smtpuser, $smtppass);//Instantiate message class
$emailtype = "HTML"; Letter type, text: text; Web page: HTML
$smtpemailto = $email;//Receive mail party, this example is registered user's email
$smtpemailfrom = $smtpusermail;//Send Mail Party, such as xxx@163.com
$emailsubject = "user account activation";//message header
//message body content
$emailbody = "Dear". $username. " :
Thank you for registering a new account at my station.
Please click on the link to activate your account.

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

If the above link is not clickable, copy it into your browser's address bar to access it, which is valid for 24 hours. ";
//Send mail
$rs = $smtp->sendmail ($smtpemailto, $smtpemailfrom, $emailsubject, $emailbody, $emailtype);
if ($rs ==1) {
$msg = ' Congratulations, your registration is successful!
Please login to your mailbox to activate your account in a timely manner! ';
}else{
$msg = $rs;
}
}
Echo $msg;

There is also a fairly useful and powerful mail-sending class to share everyone: use Phpmailer to send a message with attachments and support HTML content, directly can use OH.
active.php

If there is no accident, you register your account when you fill in the email will receive a letter sent by Helloweba, this time you directly click on the activation link, to active.php processing.

active.php receives the submitted link information, gets the value of the parameter verify, which is the activation identifier. Compare it with the user information in the data table, if there is a corresponding data set, determine whether it expires, if within the validity period will be the corresponding User table field status Set 1, that is activated, so that the activation function has been completed.

code as follows copy code

include_once (" connect.php ");//Connect to 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 to 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 succeeded! ';
}
}else{
$msg = ' error. ';
}
Echo $msg;

After successful activation, it is not useful to find the token field and you can empty it. Next we will explain the user retrieve password function, also need to use the mailbox verification, please pay attention.

Finally attach the mailbox smtp.class.php send 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;

/* Constractor */

function smtp ($relay _host = "", $smtp _port = +, $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 database Connection Class

The code is as follows Copy Code

$host = "localhost";
$db _user= "";//user name
$db _pass= "";//Password
$db _name= "Demo";//Database
$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); GMT
?>

http://www.bkjia.com/PHPjc/632757.html www.bkjia.com true http://www.bkjia.com/PHPjc/632757.html techarticle now most sites require users to use the mailbox registration, and then send the account activation email to the user registration mailbox, the user click the link can activate the account, the following I would like to introduce ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.