DIV CSS 佈局教程網

Ajax 驗證用戶名與密碼的完整實作
編輯:AJAX基礎知識     

登錄校驗是每個系統的第一道關卡。用 Ajax 來做的好處很直接:帳密錯誤時不必整頁重載,用戶改一次就能重試一次,體驗順暢得多。

一、Ajax 主體

 var xmlrequest; function createXMLHttpRequest(){ if(window.XMLHttpRequest){ xmlrequest=new XMLHttpRequest(); } else if(window.ActiveXObject){ try{ xmlrequest=new ActiveXObject("Msxm12.XMLHTTP"); } catch(e){ try{ xmlrequest=new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){} } } } function login(){ createXMLHttpRequest(); var user = document.getElementById("yhm").value; var password = document.getElementById("mm").value; if(user==""||password==""){ alert("請輸入用戶名和密碼!"); return false; } var url = "check.php?user="+user+"&password="+password; xmlrequest.open("POST",url,true); xmlrequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlrequest.onreadystatechange = function(){ if(xmlrequest.readyState == 4){ if(xmlrequest.status==200){ var msg = xmlrequest.responseText; if(msg=='1'){ alert('用戶名或密碼錯誤!'); user=""; password=""; return false; } else{ window.location.href="index1.html"; } } } } xmlrequest.send("user="+user+"&password="+password); }

二、頁面結構

 <input placeholder="用戶名" autofocus="" type="text" name="username"> <input placeholder="密碼" type="password" name="password"> <button id="dl" onclick="login()">登錄</button> 

三、服務端校驗

這裡用 SHA1 做摘要,記得把密碼和資料庫名換成你自己的:

 <?php $yhm1=$_POST['user']; $mm1=$_POST['password']; @$dp=new mysqli('localhost','root','你的密碼','你的數據庫名稱'); $yhm2=sha1($yhm1); $mm2=sha1($mm1); $query="select * from zhuce where yhm='$yhm2' and mm='$mm2'"; $result=$dp->query($query); $num=$result->num_rows; if(!$num){ echo "1"; } $dp->close(); ?> 

流程串起來:前端做非空校驗後送出請求,後端把用戶名與密碼各自做摘要,再拿摘要去資料庫匹配;匹配不到就輸出 1,前端據此提示錯誤並清空輸入框;匹配成功則導向內頁。

不過作為登錄功能,這段示範代碼在安全性上有幾處上生產前必須修正的地方,值得逐條說明:

1. 密碼不能用單純 SHA1。SHA1 速度快,這在口令存儲場景下恰恰是缺點——硬體每秒可算數十億次,彩虹表和暴力破解都很現實。應改用 password_hash()(bcrypt)或 Argon2,並在 PHP 中用 password_verify() 校驗。

2. SQL 必須參數化。把變數直接拼進 SQL 字串是 SQL 注入的標準入口。改用 mysqli 的 prepared statement 或 PDO 預處理語句。

3. 帳密不該放在 URL 上。示例裡同時拼了 query string 又 send 了 body,前者會把明文密碼寫進瀏覽器歷史與服務器訪問日誌。只保留 POST body 即可。

4. 登錄失敗不應洩露原因。「用戶名不存在」與「密碼錯誤」分開提示,等於免費提供用戶名枚舉的便利。統一提示「帳號或密碼錯誤」更妥。

5. 需要登陸失敗次數限制。加上IP或帳號級別的頻次限制與鎖定,才能抵禦暴力破解。

另外,前端校驗只是為了體驗,永遠不能替代服務端校驗——所有合法性判斷都必須在後端再走一遍。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved