search
HomeBackend DevelopmentPHP TutorialPHP结合jQuery实现找回密码_PHP

通常所说的密码找回功能不是真的能把忘记的密码找回,因为我们的密码是加密保存的,一般开发者会在验证用户信息后通过程序生成一个新密码或者生成一个特定的链接并发送邮件到用户邮箱,用户从邮箱链接到网站的重置密码模块重新设置新密码。

当然现在有的网站也有手机短信的方式找回密码,原理就是通过发送验证码来验明正身,和发送邮件验证一样,最终还是要通过重置密码来完成找回密码的流程。

一般步骤是:

1.表单输入注册时的邮箱;
2.验证用户邮箱是否正确,如果用户邮箱不存在网站的用户表中,则提示用户邮箱未注册;
3.发送邮件,如果用户邮箱确实存在用户表中,则组合用于验证用户信息的字符串,并构造URL发送到用户邮箱中;
4.用户登录邮箱收取邮件,点击URL链接到网站验证程序;
5.网站程序通过用户请求的字符串查询本地用户表,比对用户信息是否正确;
6.如果正确则转到重置密码页面重新设置新密码,反之则提示用户验证无效。

HTML

我们在找回密码的页面上放置一个要求用户输入注册时所用的邮箱,然后提交前台js来处理交互。

 
<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> 

jQuery

当用户输入完邮箱并点击提交后,jQuery先验证邮箱格式是否正确,如果正确则通过向后台sendmail.php发送Ajax请求,sendmail.php负责验证邮箱是否存在和发送邮件,并会返回相应的处理结果给前台页面,请看jQuery代码:

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

以上使用的jQuery代码很方便简洁的完成了前端交互操作,如果您有一定的jQuery基础,那上面的代码一目了然,不多解释。
当然别忘了在页面中加载jQuery库文件,有的同学经常问我说从bitsCN.com下载了demo怎么用不了,那80%是jquery或者其他文件加载路径错了导致没加载必要的文件。

PHP

sendmail.php需要验证Email是否存在系统用户表中,如果有,则读取用户信息,将用户id、用户名和密码惊醒md5加密生成一个特别的字符串作为找回密码的验证码,然后构造URL。同时我们为了控制URL链接的时效性,将记录用户提交找回密码动作的操作时间,最后调用邮件发送类发送邮件到用户邮箱,发送邮件类smtp.class.php已经打包好,请下载。

 
include_once("connect.php");//连接数据库 
 
$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){//该邮箱尚未注册! 
  echo 'noreg'; 
  exit;   
}else{ 
  $row = mysql_fetch_array($query); 
  $getpasstime = time(); 
  $uid = $row['id']; 
  $token = md5($uid.$row['username'].$row['password']);//组合验证码 
  $url = "http://www.bitsCN.com/demo/resetpass/reset.php&#63;email=".$email." 
&token=".$token;//构造URL 
  $time = date('Y-m-d H:i'); 
  $result = sendmail($time,$email,$url); 
  if($result==1){//邮件发送成功 
    $msg = '系统已向您的邮箱发送了一封邮件<br/>请登录到您的邮箱及时重置您的密码!'; 
    //更新数据发送时间 
    mysql_query("update `t_user` set `getpasstime`='$getpasstime' where id='$uid '"); 
  }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 = "bitsCN.com - 找回密码"; 
  $emailbody = "亲爱的".$email.":<br/>您在".$time."提交了找回密码请求。请点击下面的链接重置密码 
(按钮24小时内有效)。<br/><a href='".$url."'target='_blank'>".$url."</a>"; 
  $rs = $smtp->sendmail($smtpemailto, $smtpemailfrom, $emailsubject, $emailbody, $emailtype); 
 
  return $rs; 
} 

好了,这个时候你的邮箱将会收到一封来自helloweba的密码找回邮件,邮件内容中有一个URL链接,点击该链接到bitsCN.com的reset.php来验证邮箱。

 
include_once("connect.php");//连接数据库 
 
$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 = '该链接已过期!'; 
    }else{ 
      //重置密码... 
      $msg = '请重新设置密码,显示重置密码表单,<br/>这里只是演示,略过。'; 
    } 
  }else{ 
    $msg = '无效的链接'; 
  } 
}else{ 
  $msg = '错误的链接!';   
} 
echo $msg; 

reset.php首先接受参数email和token,然后根据email查询数据表t_user中是否存在该Email,如果存在则获取该用户的信息,并且和sendmail.php中的token组合方式一样构建token值,然后与url传过来的token进行对比,如果当前时间与发送邮件时的时间相差超过24小时的,则提示“该链接已过期!”,反之,则说明链接有效,并且调转到重置密码页面,最后就是用户自己设置新密码了。

小结:通过注册邮箱验证与本文邮件找回密码,我们知道发送邮件在网站开发中的应用以及它的重要性,当然,现在也流行短信验证应用,这个需要相关的短信接口对接就可以了。
最后,附上数据表t_user结构:

 
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; 

以上所述就是本文的全部内容了,希望大家能够喜欢。

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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development 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

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools