實現(xiàn)后臺管理員登錄功能
上一章節(jié)我們選擇了后臺登錄頁面,并且將驗證碼成功的加入到了登錄頁 login.html 文件中。并且創(chuàng)建了數(shù)據(jù)庫表admin,加入一條用戶名和密碼的測試數(shù)據(jù)。這一節(jié)我們就來實現(xiàn)登錄功能。
先看一個簡單功能實現(xiàn)流程圖:
有了流程圖就有了思路,順著思路就知道自己一步一步需要做什么。
首先還是要引入公共數(shù)據(jù)庫文件: config.php
通過POST方式獲取數(shù)據(jù)。使用trim()函數(shù)去除不必要的空格等。
$username = trim($_POST["username"]);//用戶名 $password = trim($_POST["password"]);//密碼 $code = $_POST["code"]; //驗證碼
對是否填寫用戶名和密碼進行驗證,驗證碼進行匹配判斷。
if($username == "") { echo"<script type='text/javascript'>alert('請?zhí)顚懹脩裘?#39;);location='login.html'; </script>"; } if($password == "") { //echo "請?zhí)顚懹脩裘?lt;br>"; echo"<script type='text/javascript'>alert('請?zhí)顚懨艽a');location='login.html'; </script>"; } if($code != $_SESSION['authcode']) { echo "<script type='text/javascript'>alert('驗證碼錯誤!');location='login.html';</script>"; }
拿著提交過來的用戶名和密碼去數(shù)據(jù)庫查找,看是否存在此用戶名以及其密碼
$sql = "select * from admin where username='".$username."' and password='".$password."'"; $result = mysqli_query($link, $sql); $rows = mysqli_fetch_array($result); if($rows) { //echo "驗證成功!<br>"; $expire_time=time()+7200; setcookie('admin_id',$rows['id'],$expire_time); setcookie('username',$rows['username'],$expire_time); echo "<script type='text/javascript'>alert('登陸成功');location='index.php';</script>"; } else { //echo "用戶名或者密碼錯誤<br>"; echo "<script type='text/javascript'>alert('用戶名或者密碼錯誤');location='login.html';</script>"; //echo "<a href='login.html'>返回</a>"; }
登陸成功后進入后臺主界面,這樣就實現(xiàn)了管理員登錄功能。