


Detailed introduction to login, registration and password modification functions implemented in PHP
May 24, 2018 pm 04:33 PMThe example in this article describes how to implement login, registration and password modification functions in PHP. Share it with everyone for your reference, the details are as follows:
Here is the interface layout and function implementation of registration, login, and password change:
1. Login
2. Forgot password
3. Free registration
Page layout:
<p id="views" class="views"> <p id="view-login" class="page-view view-login active"> <present name="wxuser"> <p id="wxuser" class="form-group text-center"> <p> <img src="{sh:$wxuser.headimgurl}"> </p> <h4 class="nickname">{sh:$wxuser.nickname}</h4> </p> </present> <!--登錄--> <p id="login" class="step"> <h4 class="popup-title login">登錄</h4> <p class="go-forget">忘記密碼</p> <form class="form-horizontal" role="form" type="get"> <p class="form-group"> <label>手機號碼</label> <input type="tel" name="tel" class="form-item" id="tel_num" placeholder="請輸入手機號碼" value=""> </p> <p class="form-group"> <label>登錄密碼</label> <input type="password" name="password" class="form-item" placeholder="請?zhí)顚懨艽a"> </p> <p class="js-help-info error"></p> </form> <p class="popup-options"> <button type="button" class="btn btn-block btn-success js-login">確認</button> </p> <p class="go-register">免費注冊</p> </p> <!--注冊--> <p id="register" class="step" style="display:none;"> <h4 class="popup-title">注冊賬號</h4> <form role="form" class="form-horizontal"> <p class="form-group"> <label>手機號碼</label> <input type="tel" name="tel" class="form-item" id="tel_num" placeholder="請輸入手機號碼" value=""> </p> <p class="form-group form-group-r"> <label>驗證碼</label> <button class="btn-sm btn-white js-sms-code" type="button">獲取驗證碼</button> <input type="text" placeholder="請?zhí)顚戲炞C碼" class="form-item" name="smscode" /> </p> <p class="form-group"> <label>登錄密碼</label> <input type="password" placeholder="設置登錄密碼" class="form-item" name="password" maxlength="30"> </p> <p class="form-group"> <label>確認密碼</label> <input type="password" placeholder="確認登錄密碼" class="form-item" name="re_password" maxlength="30"> </p> <p class="js-help-info error"> </p> </form> <p class="popup-options"> <button type="button" class="btn btn-block btn-success js-register">確認</button> </p> <p class="go-login">立即登錄</p> </p> <!--修改密碼--> <p id="changePwd" class="step" style="display:none;"> <h4 class="popup-title">修改密碼</h4> <form role="form" class="form-horizontal"> <p class="form-group"> <label>手機號碼</label> <input type="tel" name="tel" class="form-item" id="tel_num" placeholder="請輸入手機號碼" value=""> </p> <p class="form-group form-group-r"> <label>驗證碼</label> <button class="btn-sm btn-white js-sms-excode" type="button">獲取驗證碼</button> <input type="text" placeholder="請?zhí)顚戲炞C碼" class="form-item" name="smscode" /> </p> <p class="form-group"> <label>新密碼</label> <input type="password" placeholder="設置登錄密碼" class="form-item" name="password" maxlength="30"> </p> <p class="form-group"> <label>確認密碼</label> <input type="password" placeholder="確認登錄密碼" class="form-item" name="re_password" maxlength="30"> </p> <p class="js-help-info error"> </p> </form> <p class="popup-options"> <button type="button" class="btn btn-block btn-success js-changePwd">確認</button> </p> <p class="go-login">立即登錄</p> </p> </p> </p>
js processing:
<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("請求失敗"); } }); }); //發(fā)送驗證碼 $('.js-sms-code').click(function() { var tel = $('#register #tel_num').val(); if (!check.validTel(tel)) { $('.js-help-info').html('請輸入正確的手機號'); //**提示下個頁面還有 return false; } // 檢測是否已經(jīng)注冊 $.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("發(fā)送失敗"); } }); 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("發(fā)送失敗"); } }); }); //修改密碼 $('.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("請求失敗"); } }); }); //發(fā)送短信修改密碼 $('.js-sms-excode').click(function() { var tel = $('#changePwd #tel_num').val(); if (!check.validTel(tel)) { $('.js-help-info').html('請輸入正確的手機號'); //**提示下個頁面還有 return false; } // 檢測是否已經(jīng)注冊 $.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("發(fā)送失敗"); } }); 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("發(fā)送驗證碼"); $('.js-sms-excode').removeAttr("disabled"); $('.js-sms-excode').html("發(fā)送驗證碼"); } else { $("#countdown").text(time - 1); countdown(); } }, 1000); } </script>
php background Processing:
//用戶登錄 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' => '錯誤的請求')); } } //發(fā)送注冊驗證碼 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); //發(fā)送驗證碼 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) { //設置發(fā)送限制時間 session($this->smstime, time() + 50); //設置驗證碼5分鐘內有效 session($this->smscode, array('code' => $smscode, 'time' => time() + 600)); } else { //發(fā)送失敗寫入日志文件 $log = date('Y-m-d H:i:s') . " 發(fā)送失敗 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' => '錯誤的請求')); } } //發(fā)送修改密碼驗證碼 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); //發(fā)送驗證碼 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) { //設置發(fā)送限制時間 session($this->smstime, time() + 50); //設置驗證碼5分鐘內有效 session($this->smscode, array('code' => $smscode, 'time' => time() + 600)); } else { //發(fā)送失敗寫入日志文件 $log = date('Y-m-d H:i:s') . " 發(fā)送失敗 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' => '錯誤的請求')); } }
Summary:
1. SMS verification is used to register and change passwords.
2. For security reasons, front-end ajax verification. The backend also performs validation.
3. The process is reasonable and can be switched freely.
4. Comprehensive functions, including login, registration, and password modification.
The above is a detailed introduction to the login, registration and password modification functions implemented by PHP. For more related content, please pay attention to the PHP Chinese website (www.miracleart.cn)!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach
