PHP開(kāi)發(fā)留言板教程之登錄功能
登錄功能:我們先來(lái)看以下html代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>歡迎登錄</title> <style type="text/css"> *{margin: 0px;padding: 0px;} body{background:#eee;} #div{width:300px;height:400px;background:#B1FEF9;margin:0 auto;margin-top:150px; border-radius:20px;} h3{margin-left:48px;padding-top:60px;} h4{margin-left:120px;padding-top:60px;font-size: 18px;} #cnt{width:280px;height:370px;margin-left:33px;padding-top:60px;} .sub{width:70px;height:30px;border:1px solid #fff;background:#eee; margin-left:28px;margin-top:20px;} .sub1{ width:70px;height:30px;border:1px solid #fff;background:#eee;margin-left:150px;margin-top:20px;} </style> </head> <body> <div id="div"> <h3>歡迎登陸后臺(tái)管理系統(tǒng)</h3> <div id="cnt"> <form method="post" action="main.php"> 用戶名:<input type="text" placeholder="請(qǐng)輸入用戶名" name="username"> <br><br> 密 碼:<input type="password" placeholder="請(qǐng)輸入密碼" name="password"> <br><br> <input type="submit" value="登錄" class="sub"> </form> </div> </div> </body> </html>
表單提交到main.php 下面我們來(lái)分析一下main.php
當(dāng)我們登錄了之后,我們?nèi)绻泻荛L(zhǎng)一段事件沒(méi)有沒(méi)網(wǎng)頁(yè)進(jìn)行操作,當(dāng)你再次操作的時(shí)候需要去登錄,這個(gè)會(huì)用到我們的session的知識(shí)
首先我們要打開(kāi)session
????session_start();
然后我們要把鏈接數(shù)據(jù)庫(kù)的文件conn.php 引入進(jìn)來(lái)
????require_once('conn.php');
獲取表單的信息,然后把表單的信息存入session
????$name = $_POST['username'];
?? ?$pwd = md5($_POST['password']);
?? ?$_SESSION['name']=$name;
?? ?$_SESSION['pwd']=$pwd;
下面我們?nèi)?shù)據(jù)庫(kù)查詢,如果數(shù)據(jù)庫(kù)存在表單提交的信息,那么我們應(yīng)該是讓該表單提交的信息可以進(jìn)行登錄操作
????$sql = "select * from user where username='$name' and password='$pwd'";
?? ?$info = mysql_query($sql);
?? ?$row = mysql_fetch_row($info);
然后對(duì) $row 進(jìn)行判斷,存在,登錄成功,跳轉(zhuǎn)到首頁(yè)進(jìn)行添加留言的操作,否則,返回該頁(yè)面,進(jìn)行重新登錄
????if($row){
?? ??? ?echo "<script>alert('登錄成功');location.href='message.php';</script>";
?? ?}else{
?? ??? ?echo "<script>alert('登錄失敗')</script>";
?? ??? ?echo "<script>location.href='login.php';</script>";? //登錄失敗,跳轉(zhuǎn)到另外一個(gè)頁(yè)面
?? ?}
main.php 完整代碼如下:
<?php session_start(); require_once('conn.php'); $name = $_POST['username']; $pwd = md5($_POST['password']); $_SESSION['name']=$name; $_SESSION['pwd']=$pwd; $sql = "select * from user where username='$name' and password='$pwd'"; $info = mysql_query($sql); $row = mysql_fetch_row($info); if($row){ echo "<script>alert('登錄成功');location.href='message.php';</script>"; }else{ echo "<script>alert('登錄失敗')</script>"; echo "<script>location.href='login.php';</script>"; //登錄失敗,跳轉(zhuǎn)到另外一個(gè)頁(yè)面 } ?>