Home Backend Development PHP Problem How to implement the function of retrieving a forgotten password in php

How to implement the function of retrieving a forgotten password in php

Nov 24, 2020 am 10:07 AM
php

php implements the function method of forgetting the password: first enter the email address during registration through the form; then verify whether the user's email address is correct; then verify the string of user information, and construct a URL and send it to the user's email address; finally, implement the user Log in to your mailbox to receive emails and enter the password reset page to reset a new password.

How to implement the function of retrieving a forgotten password in php

Recommendation: "PHP Video Tutorial"

The operating environment of this tutorial: Windows 7 system, PHP version 5.6, This method works for all brands of computers.

PHP Mysql jQuery implements a password retrieval function

Of course, some websites now also have the method of retrieving passwords via mobile phone text messages. The principle is to verify by sending a verification code. Be clear, just like sending an email for verification, you still have to reset your password to complete the process of retrieving your password.

This article will use PHP Mysql jQuery to implement a password retrieval function. The general steps are:

1. Enter the email address during registration in the form;

2. Verify the user Is the email address correct? If the user's email address does not exist in the user table of the website, it will prompt that the user's email address is not registered;

3. Send an email. If the user's email address does exist in the user table, combine the ones used to verify the user information. string, and construct a URL and send it to the user's mailbox;

4. The user logs in to the mailbox to receive the email, and clicks the URL to link to the website verification program;

5. The website program passes the string requested by the user Query the local user table and compare whether the user information is correct;

6. If it is correct, go to the reset password page to reset a new password. Otherwise, it will prompt that the user verification is invalid.

HTML

We place a page on the password retrieval page that requires the user to enter the email address used for registration, and then submit the front-end js to handle the interaction.

<p><strong>输入您注册的电子邮箱,找回密码:</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="提 交"></p>
Copy after login

jQuery

After the user enters the email address and clicks submit, jQuery first verifies whether the email format is correct. If correct, it sends an Ajax request to the background sendmail.php, which is responsible for verification. Check whether the mailbox exists and send the email, and will return the corresponding processing results to the front page. Please see the jQuery code:

$(function(){
$("#sub_btn").click(function(){
var email = $("#email").val();
var preg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; //匹配Email
if(email==&#39;&#39; || !preg.test(email)){
$("#chkmsg").html("请填写正确的邮箱!");
}else{
$("#sub_btn").attr("disabled","disabled").val(&#39;提交中..&#39;).css("cursor","default");
$.post("sendmail.php",{mail:email},function(msg){
if(msg=="noreg"){
$("#chkmsg").html("该邮箱尚未注册!");
$("#sub_btn").removeAttr("disabled").val(&#39;提 交&#39;).css("cursor","pointer");
}else{
$(".demo").html("<h3>"+msg+"</h3>");
}
});
}
});
})
Copy after login

The jQuery code used above is very convenient and concise to complete the front-end interactive operation. If you have certain knowledge Based on jQuery, the above code is clear at a glance and requires no explanation.

Of course, don’t forget to load the jQuery library file in the page. Some students often ask me why the demo downloaded from helloweba.net cannot be used. 80% of the cases are caused by the wrong loading path of jquery or other files. Load necessary files.

PHP

#sendmail.php needs to verify whether the email exists in the system user table. If so, read the user information, use md5 encryption to generate a special character for the user id, user name and password. The string is used as the verification code to retrieve the password, and then the URL is constructed. At the same time, in order to control the timeliness of the URL link, we will record the operation time when the user submits the password retrieval action, and finally call the email sending class to send the email to the user's mailbox. The sending email class smtp.class.php has been packaged, please download it.

include_once("connect.php");//连接数据库
$email = stripslashes(trim($_POST[&#39;mail&#39;]));
$sql = "select id,username,password from `t_user` where `email`=&#39;$email&#39;";
$query = mysql_query($sql);
$num = mysql_num_rows($query);
if($num==0){//该邮箱尚未注册!
echo &#39;noreg&#39;;
exit;
}else{
$row = mysql_fetch_array($query);
$getpasstime = time();
$uid = $row[&#39;id&#39;];
$token = md5($uid.$row[&#39;username&#39;].$row[&#39;password&#39;]);//组合验证码
$url = "http://www.helloweba.net/demo/resetpass/reset.php?email=".$email."
&token=".$token;//构造URL
$time = date(&#39;Y-m-d H:i&#39;);
$result = sendmail($time,$email,$url);
if($result==1){//邮件发送成功
$msg = &#39;系统已向您的邮箱发送了一封邮件<br/>请登录到您的邮箱及时重置您的密码!&#39;;
//更新数据发送时间
mysql_query("update `t_user` set `getpasstime`=&#39;$getpasstime&#39; where id=&#39;$uid &#39;");
}else{
$msg = $result;
}
echo $msg;
}
//发送邮件
function sendmail($time,$email,$url){
include_once("smtp.class.php");
$smtpserver = ""; //SMTP服务器,如smtp.163.com
    $smtpserverport = 25; //SMTP服务器端口
    $smtpusermail = ""; //SMTP服务器的用户邮箱
    $smtpuser = ""; //SMTP服务器的用户帐号
    $smtppass = ""; //SMTP服务器的用户密码
    $smtp = new Smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); 
    //这里面的一个true是表示使用身份验证,否则不使用身份验证.
    $emailtype = "HTML"; //信件类型,文本:text;网页:HTML
    $smtpemailto = $email;
    $smtpemailfrom = $smtpusermail;
    $emailsubject = "Helloweba.com - 找回密码";
    $emailbody = "亲爱的".$email.":<br/>您在".$time."提交了找回密码请求。请点击下面的链接重置密码
(按钮24小时内有效)。<br/><a href=&#39;".$url."&#39;target=&#39;_blank&#39;>".$url."</a>";
    $rs = $smtp->sendmail($smtpemailto, $smtpemailfrom, $emailsubject, $emailbody, $emailtype);
return $rs;
}
Copy after login

Okay, at this time your mailbox will receive a password retrieval email from helloweba. There is a URL link in the email content. Click the link to reset.php of helloweba.net to verify. Mail.

include_once("connect.php");//连接数据库
$token = stripslashes(trim($_GET[&#39;token&#39;]));
$email = stripslashes(trim($_GET[&#39;email&#39;]));
$sql = "select * from `t_user` where email=&#39;$email&#39;";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
if($row){
$mt = md5($row[&#39;id&#39;].$row[&#39;username&#39;].$row[&#39;password&#39;]);
if($mt==$token){
if(time()-$row[&#39;getpasstime&#39;]>24*60*60){
$msg = &#39;该链接已过期!&#39;;
}else{
//重置密码...
$msg = &#39;请重新设置密码,显示重置密码表单,<br/>这里只是演示,略过。&#39;;
}
}else{
$msg =  &#39;无效的链接&#39;;
}
}else{
$msg =  &#39;错误的链接!&#39;;
}
echo $msg;
Copy after login

reset.php first accepts the parameters email and token, and then checks whether the email exists in the data table t_user based on the email. If it exists, obtain the user's information, and the token combination method is the same as sendmail.php Construct the token value and then compare it with the token passed by the URL. If the difference between the current time and the time when the email is sent is more than 24 hours, it will prompt "The link has expired!". Otherwise, it means that the link is valid and it will be redirected to the reset page. Set password page, and finally the user sets a new password by himself.

Summary: Through registered email verification and password retrieval through this article, we know the application of sending emails in website development and its importance. Of course, SMS verification applications are also popular now, which require related SMS interfaces. Just connect.

Finally, attach the data table t_user structure:

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;
Copy after login

The above is the detailed content of How to implement the function of retrieving a forgotten password in php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles