PHP開發(fā)留言板教學(xué)之登入功能
登入功能:我們先來(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í)
首先我們要打開session
????session_start();
然後我們要把連結(jié)資料庫(kù)的檔案conn.php 引進(jìn)進(jìn)來(lái)
????require_once('conn.php');
取得表單的信息,然後把表單的資訊存入session
????$name = $_POST['username'];
?? ?$pwd = md5($_POST['password']);
?? ?$_SESSION['name']=$name;
?? ?$_SESSION['pwd']=$pwd;
#下面我們?nèi)ベY料庫(kù)查詢,如果資料庫(kù)存在表單提交的信息,那麼我們應(yīng)該是讓該表單提交的信息可以進(jìn)行登入操作
????$sql = "select * from user where username='$name' and password='$pwd'";
?? ?$info = mysql_query($sql);
?? info$row = mysql_fetch_row($sql);
????if($row) {
?? ??? ?echo "<script>alert('登錄成功');location.href='message.php';</script>";
?? ?} alert('登入失敗')</script>";
?? ??? ?echo "<script>location.href='login.php';</script>";? //登入失敗,跳到另外一個(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è)面 } ?>