search
HomeBackend DevelopmentPHP Tutorial(Advanced) PHP+Mysql+jQuery to retrieve password

The code is as follows:

The commonly-known password retrieval function cannot really retrieve forgotten passwords, because our passwords are encrypted and saved. Generally, developers will verify the user information through The program generates a new password or generates a specific link and sends an email to the user's email. The user then links to the reset password module of the website to reset a new password.

Of course, some websites now also use mobile phone text messages to retrieve passwords. The principle is to verify your identity by sending a verification code. Just like sending an email for verification, you still have to reset your password to complete the password retrieval. process.

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 that the user's email is correct. If the user's email does not exist in the user table of the website, it will prompt that the user's email is not registered;

3. Send an email. If the user's email does exist in the user table, the combination is used to verify the user. string of information, and constructs a URL and sends it to the user's mailbox;

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

5. The website program passes the user's request Query the local user table with the string 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 the user that the verification is invalid.


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>

After the user enters the email address and clicks submit, jQuery first verifies whether the email format is correct. If it is correct, it sends an Ajax request to the background sendmail.php. sendmail.php is responsible for verifying whether the email address exists and sending 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 id="msg">"+msg+"</h3>"); 
                } 
            }); 
        } 
    }); 
})

The jQuery code used above is very convenient and concise to complete the front-end interactive operation. If you have a certain jQuery foundation, then the above code It’s clear at a glance and doesn’t require much 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.com cannot be used. 80% of the cases are caused by the wrong loading path of jquery or other files. Load necessary files.

sendmail.php needs to verify whether the email exists in the system user table. If so, read the user information, encrypt the user ID, user name and password to generate a special string using md5 encryption as a verification for retrieving the password. code, and then construct the URL. At the same time, in order to control the timeliness of the URL link, we will record the operation time of the user submitting the password retrieval action, and finally call the mail sending class to send the mail to the user's mailbox, send mail

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.com/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; 
}

Okay, at this time your mailbox You 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.com to verify your email.

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;

reset.php first accepts the parameters email and token, and then queries 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 via email in 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, the data table t_user structure is attached:

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;

The above is the content of (advanced article) PHP+Mysql+jQuery to retrieve the password. For more related content, please pay attention to the PHP Chinese website ( www.php.cn)!


Statement
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
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

See all articles

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.