PHP开发留言板教程之登录功能
登录功能:我们先来看以下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>欢迎登陆后台管理系统</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
当我们登录了之后,我们如果有很长一段事件没有没网页进行操作,当你再次操作的时候需要去登录,这个会用到我们的session的知识
首先我们要打开session
session_start();
然后我们要把链接数据库的文件conn.php 引入进来
require_once('conn.php');
获取表单的信息,然后把表单的信息存入session
$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);
然后对 $row 进行判断,存在,登录成功,跳转到首页进行添加留言的操作,否则,返回该页面,进行重新登录
if($row){
echo "<script>alert('登录成功');location.href='message.php';</script>";
}else{
echo "<script>alert('登录失败')</script>";
echo "<script>location.href='login.php';</script>"; //登录失败,跳转到另外一个页面
}
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>"; //登录失败,跳转到另外一个页面
}
?>
