PHP member Retrieve Password function Implementation Example Introduction

Source: Internet
Author: User
Tags foreach auth ereg explode php class trim jquery library server port

Set up ideas

1, user registration needs to provide an e-mail mailbox, the purpose is to use the mailbox to retrieve the password.

2, when the user forgets the password or the user name, clicks the login page "retrieves the password" the hyperlink, opens the form, and enters the registration e-mail mailbox, submits.

3, the system through the mailbox, from the database to find the user information, and update the user's password for a temporary password (such as: 12345678).

4, the system with the help of the JMail function of the user's information sent to the user's mailbox (content includes: User name, temporary password, to remind users to modify the temporary password prompt language).

5, users can login with temporary password.


Html

We placed on the page to retrieve the password to require the user to enter the registration of the mailbox, and then submitted to the front desk JS to handle the interaction.

The code is as follows Copy Code

<p><strong> Enter your registered e-mail, retrieve the password:</strong></p>
<p><input type= "text" class= "input" name= "email" id= "email" ><span id= "chkmsg" ></span></p >
<p><input type= "button" class= "btn" id= "sub_btn" value= "Submit" ></p>

Jquery

After the user enters the mailbox and clicks Submit, jquery first verifies that the mailbox is in the correct format. If correct, by sending an AJAX request to the background sendmail.php, sendmail.php is responsible for verifying that the mailbox exists and sending the message, and will return the corresponding processing results to the foreground page, see jquery code:

The code is as follows Copy Code

$ (function () {


$ ("#sub_btn"). Click (function () {


var email = $ ("#email"). Val ();


var preg =/^w+ ([-+.] w+) *@w+ ([-.] w+) *.w+ ([-.] w+) * * *; Matching Email


if (email== ' | |!preg.test (email)) {


$ ("#chkmsg"). HTML ("Please fill in the correct mailbox!") ");


}else{


$ ("#sub_btn"). attr ("Disabled", "disabled"). Val (' Submit in ... '). CSS ("cursor", "Default");


$.post ("sendmail.php", {mail:email},function (msg) {


if (msg== "Noreg") {


$ ("#chkmsg"). HTML ("This mailbox has not been registered!) ");


$ ("#sub_btn"). Removeattr ("Disabled"). Val (' Submit '). CSS ("cursor", "pointer");


}else{


$ (". Demo"). HTML ("&lt;h3&gt;" +msg+ "&lt;/h3&gt;");


}


});


}


});


})

The above jquery code is convenient and simple to complete the front-end interaction, if you have a certain jquery basis, the above code at a glance, not much explanation.

Of course, don't forget to load jquery library files in the page, some students often ask me how to download the demo from www.111cn.net How to use, that 80% is jquery or other file loading path wrong caused not to load the necessary files.
Php

Sendmail.php needs to verify whether the email exists in the System User table, if so, read the user information, wake up the user ID, username and password MD5 encryption to generate a special string as the code to retrieve the password, and then construct the URL. At the same time, in order to control the timeliness of the URL link, will record the user submitted to retrieve the password action time, the last call to Send mail class mail to the user's mailbox, send mail class smtp.class.php has been packaged, please download.

The code is as follows Copy Code

Include_once ("connect.php");//Connection database





$email = Stripslashes (Trim ($_post[' mail '));





$sql = "Select Id,username,password from ' t_user ' where ' email ' = ' $email '";


$query = mysql_query ($sql);


$num = mysql_num_rows ($query);


if ($num ==0) {//The mailbox has not yet been registered!


Echo ' Noreg ';


Exit


}else{


$row = Mysql_fetch_array ($query);


$getpasstime = time ();


$uid = $row [' id '];


$token = MD5 ($uid. $row [' username ']. $row [' password ']);//Combination Verification code


$url = "/demo/resetpass/reset.php?email=". $email. "


&amp;token= ". $token;//Construct URLs


$time = Date (' y-m-d h:i ');


$result = SendMail ($time, $email, $url);


if ($result ==1) {//message sent successfully


$msg = ' The system has sent a message to your mailbox &lt;br/&gt; please login to your mailbox and reset your password in time! ';


Update Data Send time


mysql_query ("Update" T_user ' Set ' getpasstime ' = ' $getpasstime ' where id= ' $uid ');


}else{


$msg = $result;


}


Echo $msg;


}





Send mail


function SendMail ($time, $email, $url) {


Include_once ("smtp.class.php");


$smtpserver = ""; SMTP servers, such as smtp.163.com


$smtpserverport = 25; SMTP Server port


$smtpusermail = ""; User mailboxes for SMTP servers


$smtpuser = ""; User account for SMTP server


$smtppass = ""; User password for SMTP server


$SMTP = new SMTP ($smtpserver, $smtpserverport, True, $smtpuser, $smtppass);


One of the true in this is that it means using authentication, or not using authentication.


$emailtype = "HTML"; Letter type, text: text; Web page: HTML


$smtpemailto = $email;


$smtpemailfrom = $smtpusermail;


$emailsubject = "Www.111cn.net-retrieve password";


$emailbody = "Dear". $email. " :&lt;br/&gt; you in ". $time." A request to retrieve the password was submitted. Please click the link below to reset your password


(the button is valid within 24 hours). &lt;br/&gt;&lt;a href= ' ". $url." ' target= ' _blank ' &gt; '. $url. " &lt;/a&gt; ";


$rs = $smtp-&gt;sendmail ($smtpemailto, $smtpemailfrom, $emailsubject, $emailbody, $emailtype);





return $rs;


}

Well, this time your mailbox will receive a password from Helloweba retrieve mail, the content of the message has a URL link, click on the link to www.111cn.net reset.php to verify the mailbox.

The code is as follows Copy Code

Include_once ("connect.php");//Connection database





$token = Stripslashes (Trim ($_get[' token '));


$email = Stripslashes (Trim ($_get[' email '));


$sql = "SELECT * from ' T_user ' where email= ' $email '";





$query = mysql_query ($sql);


$row = Mysql_fetch_array ($query);


if ($row) {


$MT = MD5 ($row [' id ']. $row [' username ']. $row [' password ']);


if ($mt = = $token) {


if (Time ()-$row [' Getpasstime ']&gt;24*60*60] {


$msg = ' The link has expired! ';


}else{


Reset Password ...


$msg = ' Reset password, show reset Password form,&lt;br/&gt; here just demo, skip. ';


}


}else{


$msg = ' Invalid link ';


}


}else{


$msg = ' wrong link! ';


}


Echo $msg;

reset.php first accept the parameters of email and token, and then according to the email query datasheet T_user Whether there is an email, if there is to get the user information, and build the token value in the same way as the token in sendmail.php, then compare it to the token of the URL, and if the current time differs more than 24 hours from the time the message was sent, prompt "The link has expired!" , on the other hand, the link is valid and turned to the Reset Password page, and finally the user sets the new password himself.

Summary: Through the registered mailbox authentication and this article to retrieve the password, we know that sends the mail in the website development application as well as its importance, certainly, now also popular short note authentication application, this needs the correlation short message interface docking on can.

Finally, the data sheet T_user structure is attached:

The code is as follows Copy Code

CREATE TABLE ' T_user ' (
' id ' int (one) not NULL auto_increment,
' username ' varchar not NULL,
' Password ' varchar not NULL,
' Email ' varchar not NULL,
' Getpasstime ' int (a) not NULL,
PRIMARY KEY (' id ')
) Engine=myisam DEFAULT Charset=utf8;

smtp.class.php class file

The code is as follows Copy Code

<?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 = =, $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. "
;";
}
}
}
?>

The last side has a database connection class, here will not introduce the big everyone can find the relevant database connection MySQL class Oh.

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.