PHP实现的登录,注册及密码修改功能分析

yipeiwu_com5年前PHP代码库

本文实例讲述了PHP实现登录,注册及密码修改功能的方法。分享给大家供大家参考,具体如下:

这里介绍注册,登录,修改密码的界面布局与功能实现:

1.登录

2.忘记密码

3.免费注册

页面布局:

<div id="views" class="views">
  <div id="view-login" class="page-view view-login active">
    <present name="wxuser">
      <div id="wxuser" class="form-group text-center">
        <div>
          <img src="{sh:$wxuser.headimgurl}">
        </div>
        <h4 class="nickname">{sh:$wxuser.nickname}</h4>
      </div>
    </present>
    <!--登录-->
    <div id="login" class="step">
      <h4 class="popup-title login">登录</h4>
      <div class="go-forget">忘记密码</div>
      <form class="form-horizontal" role="form" type="get">
        <div class="form-group">
          <label>手机号码</label>
          <input type="tel" name="tel" class="form-item" id="tel_num" placeholder="请输入手机号码" value="">
        </div>
        <div class="form-group">
          <label>登录密码</label>
          <input type="password" name="password" class="form-item" placeholder="请填写密码">
        </div>
        <div class="js-help-info error"></div>
      </form>
      <div class="popup-options">
        <button type="button" class="btn btn-block btn-success js-login">确认</button>
      </div>
      <div class="go-register">免费注册</div>
    </div>
    <!--注册-->
    <div id="register" class="step" style="display:none;">
      <h4 class="popup-title">注册账号</h4>
      <form role="form" class="form-horizontal">
        <div class="form-group">
          <label>手机号码</label>
          <input type="tel" name="tel" class="form-item" id="tel_num" placeholder="请输入手机号码" value="">
        </div>
        <div class="form-group form-group-r">
          <label>验证码</label>
          <button class="btn-sm btn-white js-sms-code" type="button">获取验证码</button>
          <input type="text" placeholder="请填写验证码" class="form-item" name="smscode" />
        </div>
        <div class="form-group">
          <label>登录密码</label>
          <input type="password" placeholder="设置登录密码" class="form-item" name="password" maxlength="30">
        </div>
        <div class="form-group">
          <label>确认密码</label>
          <input type="password" placeholder="确认登录密码" class="form-item" name="re_password" maxlength="30">
        </div>
        <div class="js-help-info error">
        </div>
      </form>
      <div class="popup-options">
        <button type="button" class="btn btn-block btn-success js-register">确认</button>
      </div>
      <div class="go-login">立即登录</div>
    </div>
    <!--修改密码-->
    <div id="changePwd" class="step" style="display:none;">
      <h4 class="popup-title">修改密码</h4>
      <form role="form" class="form-horizontal">
        <div class="form-group">
          <label>手机号码</label>
          <input type="tel" name="tel" class="form-item" id="tel_num" placeholder="请输入手机号码" value="">
        </div>
        <div class="form-group form-group-r">
          <label>验证码</label>
          <button class="btn-sm btn-white js-sms-excode" type="button">获取验证码</button>
          <input type="text" placeholder="请填写验证码" class="form-item" name="smscode" />
        </div>
        <div class="form-group">
          <label>新密码</label>
          <input type="password" placeholder="设置登录密码" class="form-item" name="password" maxlength="30">
        </div>
        <div class="form-group">
          <label>确认密码</label>
          <input type="password" placeholder="确认登录密码" class="form-item" name="re_password" maxlength="30">
        </div>
        <div class="js-help-info error">
        </div>
      </form>
      <div class="popup-options">
        <button type="button" class="btn btn-block btn-success js-changePwd">确认</button>
      </div>
      <div class="go-login">立即登录</div>
    </div>
  </div>
</div>

js处理:

<script type="text/javascript">
var tel = '';
$(function() {
  var check = {
    checkPwd: function(password) {
      if (typeof password == 'undefined' || password == '') {
        return false;
      }
      return true;
    },
    checkSmscode: function(code) {
      if (typeof code == 'undefined' || code == '') {
        return false;
      }
      return true;
    },
    validTel: function(value) {
      return /^((\+86)|(86))?(1)\d{10}$/.test('' + value);
    }
  }
  //登录
  $(".js-login").click(function() {
    var tel = $("#login").find("input[name='tel']").val();
    if (!check.validTel(tel)) {
      $('.js-help-info').html('请输入正确的手机号'); //**提示下个页面还有
      return false;
    }
    var password = $("#login").find("input[name='password']").val();
    if (!check.checkPwd(password)) {
      $('.js-help-info').html('请输入密码');
      return false;
    }
    $('.js-login').attr("disabled", "disabled");
    $.ajax({
      url: "{sh::U('Home/userLogin')}",
      type: 'POST',
      dataType: "json",
      data: {
        tel: tel,
        password: password
      },
      success: function(response) {
        if (response.result) {
          location.href = response.href;
        } else {
          setTimeout(function() {
            $('.js-login').removeAttr("disabled");
          }, 500);
          $('.js-help-info').html(response.error);
        }
      },
      error: function() {
        $('.js-help-info').html("请求失败");
      }
    });
  });
  //注册
  $(".js-register").click(function() {
    var tel = $("#register").find("input[name='tel']").val();
    if (!check.validTel(tel)) {
      $('.js-help-info').html('请输入正确的手机号'); //**提示下个页面还有
      return false;
    }
    var password = $("#register input[name='password']").val();
    var smscode = $("#register input[name='smscode']").val();
    var re_password = $("#register input[name='re_password']").val();
    if (!check.checkSmscode(smscode)) {
      $('.js-help-info').html('请输入验证码');
      return false;
    }
    if (!check.checkPwd(password)) {
      $('.js-help-info').html('请输入登录密码');
      return false;
    }
    if (!check.checkPwd(re_password)) {
      $('.js-help-info').html('请输入确认密码');
      return false;
    } else if (password != re_password) {
      $('.js-help-info').html('两次输入的密码不一致');
      return false;
    }
    $('.js-login').attr("disabled", "disabled");
    $.ajax({
      url: "{sh::U('Home/userRegister')}",
      type: 'POST',
      dataType: "json",
      data: {
        tel: tel,
        password: password,
        smscode: smscode
      },
      success: function(response) {
        if (response.result) {
          location.href = response.href;
        } else {
          setTimeout(function() {
            $('.js-login').removeAttr("disabled");
          }, 500);
          $('.js-help-info').html(response.error);
        }
      },
      error: function() {
        $('.js-help-info').html("请求失败");
      }
    });
  });
  //发送验证码
  $('.js-sms-code').click(function() {
    var tel = $('#register #tel_num').val();
    if (!check.validTel(tel)) {
      $('.js-help-info').html('请输入正确的手机号'); //**提示下个页面还有
      return false;
    }
    // 检测是否已经注册
    $.ajax({
      url: "{sh::U('Home/checkTel')}",
      type: 'POST',
      dataType: "json",
      async: false,
      data: {
        tel: tel
      },
      success: function(json) {
        checkRes = json.status;
      },
      error: function(json) {
        $('.js-help-info').html("发送失败");
      }
    });
    if (checkRes == 1) {
      $('.js-help-info').html("已是注册用户");return false;
    }
    if (checkRes == 3) {
      $('.js-help-info').html("错误的请求");return false;
    }
    $(this).attr("disabled", "disabled").html("<span style='color:#666'><span id='countdown'>60</span>s 后再试</span>");
    countdown();
    $.ajax({
      url: "{sh::U('Home/sendSmscode')}",
      type: 'POST',
      dataType: "json",
      data: {
        tel: tel
      },
      success: function() {},
      error: function() {
        $('.js-help-info').html("发送失败");
      }
    });
  });
  //修改密码
  $('.go-forget').click(function() {
    var tel = $('#login #tel_num').val();
    $("#login").hide();
    $("#register").hide();
    $("#changePwd").show();
    $("#changePwd #tel_num").val(tel).focus();
    $('.js-help-info').html('');
  });
  //免费注册
  $('.go-register').click(function() {
    var tel = $('#login #tel_num').val();
    $("#login").hide();
    $("#changePwd").hide();
    $("#register").show();
    $("#register #tel_num").val(tel).focus();
    $('.js-help-info').html('');
  });
  //立即登录
  $('#changePwd .go-login').click(function() {
    var tel = $('#changePwd #tel_num').val();
    $("#register").hide();
    $("#changePwd").hide();
    $("#login").show();
    $("#login #tel_num").val(tel).focus();
    $('.js-help-info').html('');
  });
  //立即登录
  $('#register .go-login').click(function() {
    var tel = $('#register #tel_num').val();
    $("#register").hide();
    $("#changePwd").hide();
    $("#login").show();
    $("#login #tel_num").val(tel).focus();
    $('.js-help-info').html('');
  });
  $('.js-changePwd').click(function() {
    var tel = $("#changePwd").find("input[name='tel']").val();
    if (!check.validTel(tel)) {
      $('.js-help-info').html('请输入正确的手机号'); //**提示下个页面还有
      return false;
    }
    var password = $("#changePwd input[name='password']").val();
    var smscode = $("#changePwd input[name='smscode']").val();
    var re_password = $("#changePwd input[name='re_password']").val();
    if (!check.checkSmscode(smscode)) {
      $('#changePwd .js-help-info').html('请输入验证码');
      return false;
    }
    if (!check.checkPwd(password)) {
      $('#changePwd .js-help-info').html('请输入新密码');
      return false;
    }
    if (!check.checkPwd(re_password)) {
      $('#changePwd .js-help-info').html('请输入确认密码');
      return false;
    } else if (password != re_password) {
      $('#changePwd .js-help-info').html('两次输入的密码不一致');
      return false;
    }
    $.ajax({
      url: "{sh::U('Home/changePwd')}",
      type: "POST",
      dataType: "json",
      data: {
        tel: tel,
        password: password,
        smscode: smscode
      },
      success: function(response) {
        if (response.result) {
          location.href = response.href;
        } else {
          setTimeout(function() {
            $('.js-login').removeAttr("disabled");
          }, 500);
          $('.js-help-info').html(response.error);
        }
      },
      error: function() {
        $('.js-help-info').html("请求失败");
      }
    });
  });
  //发送短信修改密码
  $('.js-sms-excode').click(function() {
    var tel = $('#changePwd #tel_num').val();
    if (!check.validTel(tel)) {
      $('.js-help-info').html('请输入正确的手机号'); //**提示下个页面还有
      return false;
    }
    // 检测是否已经注册
    $.ajax({
      url: "{sh::U('Home/checkTel')}",
      type: 'POST',
      dataType: "json",
      async: false,
      data: {
        tel: tel
      },
      success: function(json) {
        checkRes = json.status;
      },
      error: function(json) {
        $('.js-help-info').html("发送失败");
      }
    });
    if (checkRes == 2) {
      $('.js-help-info').html("号码尚未注册");return false;
    }
    if (checkRes == 3) {
      $('.js-help-info').html("错误的请求");return false;
    }
    $(this).attr("disabled", "disabled").html("<span style='color:#666'><span id='countdown'>60</span>s 后再试</span>");
    countdown();
    $.ajax({
      url: "{sh::U('Home/sendSmsexcode')}",
      type: 'POST',
      dataType: "json",
      data: {
        tel: tel
      },
      success: function(data) {},
      error: function() {
        $('.js-help-info').html("请求失败");
      }
    });
  });
});
function countdown() { // 递归 验证码倒计时
  setTimeout(function() {
    var time = $("#countdown").text();
    if (time == 1) {
      $('.js-sms-code').removeAttr("disabled");
      $('.js-sms-code').html("发送验证码");
      $('.js-sms-excode').removeAttr("disabled");
      $('.js-sms-excode').html("发送验证码");
    } else {
      $("#countdown").text(time - 1);
      countdown();
    }
  }, 1000);
}
</script>

php后台处理:

//用户登录
public function userLogin() {
  if(IS_AJAX && !$this->member) {
   $tel = $this->_post('tel', 'trim');
   $password = $this->_post('password', 'trim,md5');
   $member = M('Member')->where(array('tel' => $tel))->find();
   if ($member && $member['password'] === $password) {
    //检测是否存在微信用户需要绑定
    if ($member['wxuser_id'] == 0 && $this->wxuser) {
     M('Member')->where(array('id' => $member['id']))->save(array('wxuser_id' => $this->wxuser_id));
    }
    $href = session(LASTREQUEST);
    session(MEMBER, $member['id']);
    session(LASTREQUEST, null);
    $this->ajaxReturn(array('result' => true, 'href' => $href ? $href : U('Member/index')));
   } else {
    if (empty($member)) {
     $this->ajaxReturn(array('result' => false, 'error' => '手机号尚未注册.'));
    } else {
     $this->ajaxReturn(array('result' => false, 'error' => '密码不正确.'));
    }
   }
  } else {
   $this->ajaxReturn(array('result' => false, 'error' => '非法请求.'));
  }
}
// 用户退出
public function userLogout() {
  session(WXUSER, null);
  session(MEMBER, null);
  $this->success('退出成功',U('Store/Member/index'));
}
// 用户注册
public function userRegister() {
  $tel = $this->_post('tel', 'trim');
  $password = $this->_post('password', 'trim,md5');
  $smscode = $this->_post('smscode', 'trim');
  $session_smscode = session($this->smscode);
  $user_exit = M('Member')->where(array('tel' => $tel))->find();
  if (!preg_match("/1[3458]{1}\d{9}$/", $tel) && $user_exit) {
   $this->ajaxReturn(array('result' => false, 'error' => '手机号不合法'));
  }
  $memberModel = M('Member');
  // 检测是否已注册
  $member = $memberModel-> where(array('tel' =>$tel,'status'=>1))->find();
  if (!empty($member)) {
   $this->ajaxReturn(array('result' => false, 'error' => '已是注册用户'));
  }
  if (time() > $session_smscode['time'] || $smscode != $session_smscode['code']) {
   $this->ajaxReturn(array('result' => false, 'error' => '验证码不正确')); //--调试,先把验证功能关闭
  }
  $data = array('tel' => $tel, 'password' => $password, 'wxuser_id' => intval($this->wxuser_id), 'addtime' => time());
  $insert_id = $memberModel->add($data);
  if ($insert_id) {
   $href = session(LASTREQUEST);
   session(MEMBER, $insert_id); //*****只是一个id值
   $this->ajaxReturn(array('result' => true, 'href' => $href ? $href : U('Member/index')));
  } else {
   $this->ajaxReturn(array('result' => false, 'error' => '操作失败', 'msg' => M('Member')->getError()));
  }
}
//用户更改密码
public function changePwd(){
  $tel = $this->_post('tel','trim');
  $password = $this ->_post('password','trim');
  $smscode = $this ->_post('smscode','trim');
  $session_smscode = session($this ->smscode);
  if (time() > $session_smscode['time'] || $smscode != $session_smscode['code']) {
   $this->ajaxReturn(array('result' => false, 'error' => '验证码不正确')); //--调试成功
  }
  $data = array('password' => md5($password), 'addtime' => time());
  $memberModel = M('Member');
  // 检测是否已注册
  $member = $memberModel-> where(array('tel' =>$tel,'status'=>1))->find();
  if (empty($member)) {
   $this->ajaxReturn(array('result' => false, 'error' => '号码尚未注册'));
  }
  if ($memberModel->where(array('tel'=> $tel))->save($data)) {
   $href = session(LASTREQUEST);
   session(MEMBER, $member['id']);
   $this->ajaxReturn(array('result' => true, 'href' => $href ? $href : U('Member/index')));
  } else {
   $this->ajaxReturn(array('result' => false, 'error' => '操作失败', 'msg' => M('Member')->getError()));
  }
}
// ajax检测号码是否注册
public function checkTel() {
  $tel = $this->_post('tel', 'trim');
  if (IS_AJAX && preg_match("/1[3458]{1}\d{9}$/",$tel)) {
   $memberModel = M('Member');
   $member = $memberModel->where(array('tel'=>$tel,'status'=>1))->find();
   if (!empty($member)) {
    $this->ajaxReturn(array('status' => 1, 'info' => '已注册'));
   } else {
    $this->ajaxReturn(array('status' => 2, 'info' => '未注册'));
   }
  } else {
   $this->ajaxReturn(array('status' => 3, 'info' => '错误的请求'));
  }
}
//发送注册验证码
public function sendSmscode() {
  session($this->smstime, null);
  $smstime = session($this->smstime);
  $tel = $this->_post('tel', 'trim');
  if (IS_AJAX && (!$smstime || time() > $smstime) && preg_match("/1[3458]{1}\d{9}$/",$tel)) {
   $smscode = rand(1000, 9999);
   //发送验证码
   require LIB_PATH . 'ORG/Taobao-sdk-php/TopSdk.php';
   $c = new TopClient;
   $c->appkey = '23307560'; // 原23294081
   $c->secretKey = '21ef24dd4c51e20693c5db0983c433e7'; // 原0402169f466d8fed780e7f07edd25177
   $req = new AlibabaAliqinFcSmsNumSendRequest;
   $req->setSmsType("normal");
   $req->setSmsFreeSignName("注册验证");
   $req->setSmsParam('{"code":"'. $smscode .'","product":"【多多助店宝】"}');
   $req->setRecNum("{$tel}");
   $req->setSmsTemplateCode("SMS_5056863");
   $resp = $c->execute($req);
   if(!$resp->code) {
    //设置发送限制时间
    session($this->smstime, time() + 50);
    //设置验证码5分钟内有效
    session($this->smscode, array('code' => $smscode, 'time' => time() + 600));
   } else {
    //发送失败写入日志文件
    $log = date('Y-m-d H:i:s') . " 发送失败 sub_code:{$resp->sub_code} sub_msg:{$resp->sub_msg}" . PHP_EOL;
    file_put_contents(RUNTIME_PATH . 'Log/smscode.log', $log, FILE_APPEND);
   }
   $this->ajaxReturn(array('result' => !$resp->code));
  } else {
   $this->ajaxReturn(array('result' => false, 'error' => '错误的请求'));
  }
}
//发送修改密码验证码
public function sendSmsexcode(){
  session($this->smstime, null);
  $smstime = session($this->smstime);
  $tel = $this->_post('tel', 'trim');
  if (IS_AJAX && (!$smstime || time() > $smstime) && preg_match("/1[3458]{1}\d{9}$/",$tel)) {
   $smscode = rand(1000, 9999);
   //发送验证码
   require LIB_PATH . 'ORG/Taobao-sdk-php/TopSdk.php';
   $c = new TopClient;
   $c->appkey = '23307560'; // 原23294081
   $c->secretKey = '21ef24dd4c51e20693c5db0983c433e7'; // 原0402169f466d8fed780e7f07edd25177
   $req = new AlibabaAliqinFcSmsNumSendRequest;
   $req->setSmsType("normal");
   $req->setSmsFreeSignName("变更验证"); //短信签名固定,不可以换其他字
   $req->setSmsParam('{"code":"'. $smscode .'","product":"【多多助店宝】"}');
   $req->setRecNum("{$tel}");
   $req->setSmsTemplateCode("SMS_5056861");
   $resp = $c->execute($req);
   if(!$resp->code) {
    //设置发送限制时间
    session($this->smstime, time() + 50);
    //设置验证码5分钟内有效
    session($this->smscode, array('code' => $smscode, 'time' => time() + 600));
   } else {
    //发送失败写入日志文件
    $log = date('Y-m-d H:i:s') . " 发送失败 sub_code:{$resp->sub_code} sub_msg:{$resp->sub_msg}" . PHP_EOL;
    file_put_contents(RUNTIME_PATH . 'Log/smscode.log', $log, FILE_APPEND);
   }
   $this->ajaxReturn(array('result' => !$resp->code));
  } else {
   $this->ajaxReturn(array('result' => false, 'error' => '错误的请求'));
  }
}

小结:

1.注册与修改密码用到了短信验证。
2.安全起见,前端ajax验证。后端亦进行验证。
3.流程合理,切换自如。
4.功能全面,登录,注册,密码修改齐全。

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP+MySQL会员系统开发专题》、《PHP微信开发技巧汇总》、《PHP编码与转码操作技巧汇总》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP使用HTML5 FileApi实现Ajax上传文件功能示例

PHP使用HTML5 FileApi实现Ajax上传文件功能示例

本文实例讲述了PHP使用HTML5 FileApi实现Ajax上传文件功能。分享给大家供大家参考,具体如下: FileApi是HTML5的一个新特性,有了这个新特性,js就可以读取本地的...

浅析PKI加密解密 OpenSSL

点击下载OpenSSL window与linux要区分的 解压文件 双击: Win32OpenSSL-0_9_8l_95895.exe 安装完毕后 \OpenSSL\bin\opens...

IIS下PHP的三种配置方式对比

 在Windows IIS 6.0下配置PHP,通常有CGI、ISAPI和FastCGI三种配置方式,这三种模式都可以在IIS 6.0下成功运行,下面我就讲一下这三种方式配置的区别和性能...

WordPress判断用户是否登录的代码

is_user_logged_in() 说明 根据当前访问者是否登录返回布尔值true或false。 参数 该函数不接受任何参数。 用法 复制代码 代码如下: <?php if (...

自制PHP框架之路由与控制器

自制PHP框架之路由与控制器

我们为什么要使用路由?原因1:一个更漂亮的URI 1.URI的改进 刚刚开始学PHP时,我们一定写过blog.php?id=1之类的URI,使用GET方式获取参数。这样的URI有...