Simple implementation of PHP member password retrieval function, php member password retrieval

Source: Internet
Author: User
Tags ereg preg

Simple implementation of PHP member password retrieval function, php member password retrieval

Setting ideas

1, the user needs to provide a E-MAIL mailbox, the purpose is to use the mailbox to retrieve the password.

2. When the user forgets the password or user name, click the login page "retrieve password" hyperlink, open the form, and enter the registered E-MAIL mailbox, submit.

3. The system finds the user information from the database through the mailbox, and updates the user's password to a temporary password (for example, 12345678 ).

4. The system uses the Jmail function to send the user's information to the user's mailbox (including the user name, temporary password, and prompt to remind the user to change the temporary password in a timely manner ).

5. You can log on with a temporary password.

HTML

On the password retrieval page, we place an email that requires the user to enter the account used for registration, and then submit the front-end js to process the interaction.

The Code is as follows:

<P> <strong> enter your registered email address and retrieve the password: </strong> </p> <input type = "text" class = "input" name = "email" id = "email"> <span id = "chkmsg "> </span> </p> <input type =" button "class =" btn "id =" sub_btn "value =" Submit "> </p>

JQuery

After you enter your email address and click Submit, jQuery first verifies that the email address format is correct. If yes, it sends the email address to the backend. php sends Ajax requests, sendmail. php is responsible for verifying whether the mailbox exists and sending emails, and returning the corresponding processing results to the front-end page. Please refer to the jQuery code:

The Code is as follows:

$ (Function () {$ ("# sub_btn "). click (function () {var email = $ ("# email "). val (); var preg =/^ w + ([-+.] w +) * @ w + ([-.] w + )*. w + ([-.] w +) * // match the Email if (email = ''|! Preg. test (email) {$ ("# chkmsg" pai.html ("please fill in the correct email! ");} Else {$ (" # sub_btn "). attr ("disabled", "disabled" 2.16.val('submit..'resumable .css ("cursor", "default"); $. post ("sendmail. php ", {mail: email}, function (msg) {if (msg =" noreg ") {$ (" # chkmsg "..html (" this email has not been registered! "); $ (" # Sub_btn "). removeAttr ("disabled "). val ('submit 'character .css ("cursor", "pointer");} else {$ (". demo "cmd.html (" 

The above jQuery code is convenient and concise to complete front-end interaction operations. If you have a certain jQuery Foundation, the above Code is clear and not explained.

Of course, don't forget to load the jQuery library file on the page. Some people often ask me why I cannot download the demo from the Internet, that 80% is because jquery or other file loading paths are incorrect, leading to unnecessary file loading.

PHP

Sendmail. php needs to verify whether the Email exists in the System user table. If there is, read the user information and wake up the user ID, user name, and password with md5 encryption to generate a special string as the verification code for password retrieval, then construct the URL. In addition, in order to control the timeliness of URL links, we will record the operation time when the user submitted the password retrieval action, and finally call the mail sending class to send the mail to the user's mailbox, and send the mail class smtp. class. php has been packaged. download it.

The Code is as follows:

Include_once ("connect. php "); // connect to the 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) {// This email address is not registered yet! Echo 'noreg '; exit;} else {$ row = mysql_fetch_array ($ query); $ getpasstime = time (); $ uid = $ row ['id']; $ token = md5 ($ uid. $ row ['username']. $ row ['Password']); // combined Verification Code $ url = "/demo/resetpass/reset. php? Email = ". $ email. "& token = ". $ token; // construct the URL $ time = date ('Y-m-d H: I '); $ result = sendmail ($ time, $ email, $ url ); if ($ result = 1) {// email sent successfully $ msg = 'the system has sent an email to your mailbox <br/> Please log on to your mailbox and reset your password in time! '; // Update the data sending time mysql_query ("update 't_ user' set 'getpasstime' =' $ getpasstime 'where id =' $ uid '");} else {$ msg = $ result;} echo $ msg;} // send email function sendmail ($ time, $ email, $ url) {include_once ("smtp. class. php "); $ smtpserver =" "; // SMTP server, such as smtp.163.com $ smtpserverport = 25; // SMTP server port $ smtpusermail = ""; // SMTP server user email $ smtpuser = ""; // SMTP server user account $ smtppass = ""; // SMTP server user password $ smtp = new Smtp ($ Smtpserver, $ smtpserverport, true, $ smtpuser, $ smtppass); // here, true indicates that authentication is used; otherwise, authentication is not used. $ emailtype = "HTML"; // mail type, text: text; webpage: HTML $ smtpemailto = $ email; $ smtpemailfrom = $ smtpusermail; $ emailsubject = "www.jb51.net-retrieve password"; $ emailbody = "dear ". $ email. ": <br/> you are in ". $ time. "A password retrieval request is submitted. Click the link below to reset the password (the button is valid within 24 hours ). <Br/> <a href = '". $ url. "'target = '_ blank'> ". $ url. "</a>"; $ rs = $ smtp-> sendmail ($ smtpemailto, $ smtpemailfrom, $ emailsubject, $ emailbody, $ emailtype); return $ rs ;}

Now, your mailbox will receive a password retrieval email from helloweba. The email contains a URL link and click the link to reset. php to verify the email address.

The Code is as follows:

Include_once ("connect. php "); // connect to the 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']> 24*60*60) {$ msg = 'this link has expired! ';} Else {// reset the password... $ msg =' Please reset the password to display the password reset form. <br/> here is only a demonstration, skipped. ';}} Else {$ msg = 'invalid link';} else {$ msg = 'incorrect link! ';} Echo $ msg;

Reset. php first accepts the parameter email and token, and then queries whether the email exists in the t_user data table based on the Email. If so, it obtains the information of the user and sendmail. in php, the token combination method is the same as the token value, and then compare it with the token passed in the url. If the current time differs from the time when the email is sent by more than 24 hours, the message "this link has expired!" is displayed! ", Otherwise, the link is valid, and is transferred to the Password Reset page. Finally, the user sets the new password.

Summary:Through email registration verification and password retrieval in this article, we know the application of email sending in website development and its importance. Of course, the text message verification application is also popular now, this requires the connection of related SMS interfaces.

Finally, the t_user structure of the data table is attached:

The Code is as follows:

CREATE TABLE `t_user` ( `id` int(11) NOT NULL auto_increment, `username` varchar(30) NOT NULL, `password` varchar(32) NOT NULL, `email` varchar(50) NOT NULL, `getpasstime` int(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Smtp. class. php class file

The Code is as follows:

<?phpclass 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(www.jb51.net): $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");}// authif ($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 . ";";}}}?>

There is a database connection class at the end. Here we will not introduce the related database connection mysql class.

The simple implementation of the above PHP member password retrieval function is all the content shared by the editor. I hope to give you a reference and support for the help house.

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.