PHP開發(fā)留言板教程之登錄功能
登錄功能:我們先來看以下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ǒng)</h3> <div id="cnt"> <form method="post" action="main.php"> 用戶名:<input type="text" placeholder="請輸入用戶名" name="username"> <br><br> 密 碼:<input type="password" placeholder="請輸入密碼" name="password"> <br><br> <input type="submit" value="登錄" class="sub"> </form> </div> </div> </body> </html>
表單提交到main.php 下面我們來分析一下main.php
當我們登錄了之后,我們?nèi)绻泻荛L一段事件沒有沒網(wǎng)頁進行操作,當你再次操作的時候需要去登錄,這個會用到我們的session的知識
首先我們要打開session
session_start();
然后我們要把鏈接數(shù)據(jù)庫的文件conn.php 引入進來
require_once('conn.php');
獲取表單的信息,然后把表單的信息存入session
$name = $_POST['username'];
$pwd = md5($_POST['password']);
$_SESSION['name']=$name;
$_SESSION['pwd']=$pwd;
下面我們?nèi)?shù)據(jù)庫查詢,如果數(shù)據(jù)庫存在表單提交的信息,那么我們應該是讓該表單提交的信息可以進行登錄操作
$sql = "select * from user where username='$name' and password='$pwd'";
$info = mysql_query($sql);
$row = mysql_fetch_row($info);
然后對 $row 進行判斷,存在,登錄成功,跳轉(zhuǎ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)到另外一個頁面
}
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)到另外一個頁面 } ?>