PHP user registration email verification activation account example _ PHP Tutorial

Source: Internet
Author: User
Tags ereg
PHP user registration email verification activation account example. Currently, most websites require users to register using their email addresses, and then send an account activation email to the user's registered email address. the user can click the link to activate the account, next, I will introduce that most websites now require users to register using their email addresses, and then send an account activation email to the user's registered email address. the user can click the link to activate the account, the following describes the specific methods.

Functional requirements

PHP program development: When a user registers for a website, the user needs to activate the account through the email link. after the user registers (the user information is written to the database), the user does not log on to the mailbox to activate the account, users who have not activated the account are automatically deleted after 24 hours. after the activation link expires, users can also use this information to register on the website.

Prepare a data table

The field Email in the user information table is very important. it can be used to verify the user, retrieve the password, or even collect the user information for Email marketing for the website. The following is the table structure of the user information table t_user:

The code is as follows:

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' mailbox ',
'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. you can enter registration information, including the user name, password, and email address.

The code is as follows:

You need to perform necessary front-end verification for user input. for the form verification function, we recommend that you refer to the article on this site: the example explains the application of the form verification plug-in Validation. This article skipped the front-end verification code, in addition, there should be an input box asking the user to repeat the password on the page. this is just a bit lazy.
Register. php

The user submits the registration information to register. php for processing. Register. php requires writing data and sending emails.

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

The code is as follows:


Include_once ("connect. php"); // connect to the database
Include_once ("smtp. class. php"); // mail sending class

Then we need to filter the information submitted by the user and verify whether the user name 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 'user name already exists. please change to another user name ';
Exit;
}

Then, we encrypt the user password and construct the activation identifier:

The code is as follows:

$ Password = md5 (trim ($ _ POST ['password']); // encrypt the password
$ Email = trim ($ _ POST ['email ']); // email
$ Regtime = time ();

$ Token = md5 ($ username. $ password. $ regtime); // Create an identifier for activation
$ 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 identifier, which consists of the 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. you can activate the account within this period. In this example, activation is effective within 24 hours. Finally, insert these fields into the t_user table.

After the data is inserted successfully, call the Mail sending class to send the activation information to the user's registered email address. Note that the constructed activation identifier is used as a complete URL as the activation link when the user clicks, the following code details:

The code is as follows:

If (mysql_insert_id ()){
$ Smtpserver = ""; // SMTP server, for example, smtp.163.com
$ Smtpserverport = 25; // SMTP server port, usually 25
$ Smtpusermail = ""; // The user mailbox of the SMTP server, such as the xxx@163.com
$ Smtpuser = ""; // User account xxx@163.com for SMTP server
$ Smtppass = ""; // SMTP server user password
$ Smtp = new Smtp ($ smtpserver, $ smtpserverport, true, $ smtpuser, $ smtppass); // instantiate the mail class
$ Emailtype = "HTML"; // mail type, text: text; webpage: HTML
$ Smtpemailto = $ email; // the recipient. In this example, it is the Email of the registered user.
$ Smtpemailfrom = $ smtpusermail; // sender, such as a xxx@163.com
$ Emailsubject = "User Account activation"; // mail title
// Subject content
$ Emailbody = "dear". $ username .":
Thank you for registering a new account on our site.
Click the link to activate your account.

'_ Blank'>/demo/register/active. php? Verify = ". $ token ."

If the above link cannot be clicked, copy it to your browser's address bar for access. This link is valid for 24 hours. ";
// Send an email
$ Rs = $ smtp-> sendmail ($ smtpemailto, $ smtpemailfrom, $ emailsubject, $ emailbody, $ emailtype );
If ($ rs = 1 ){
$ Msg = 'congratulations, registration successful!
Please log on to your mailbox and promptly activate your account! ';
} Else {
$ Msg = $ rs;
}
}
Echo $ msg;

Another useful and powerful email sending class is to share with you: you can use PHPMailer to send emails with attachments and HTML content.
Active. php

If nothing happens, the Email you entered during account registration will receive an Email sent by helloweba. at this time, you click the activation link and submit it to active. php for processing.

Active. php receives the submitted link information and obtains the verify parameter value, that is, the activation identifier. Compare it with the user information in the data table. if there is a corresponding dataset, determine whether it has expired. if it is within the validity period, set the status field of the corresponding user table to 1, that is, it is activated, this completes the activation function.

The code is as follows:

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']) {// 24 hour
$ Msg = 'Your activation has expired. please log on 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, the token field is useless. you can clear it. Next, we will explain the user password retrieval function and use email verification. please stay tuned.

Finally, the mail smtp. class. php sending class is attached.

The code is as follows:

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

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, ""))){
$ 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

The code is as follows:

$ 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); // Beijing time
?>

...

Related Article

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.