PHP中session的基础应用二

  在介绍完session的基本用法之后,来做一个简单的应用,即利用session实现简单的登录。

  先编写登录的前端页面,login.html。

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
 <title>登录</title>
 <style type="text/css">
  body {
   background: url(images/bg.png);
  }
  
  .clear {
   clear: both;
  }
  
  .login {
   width: 370px;
   margin: 100px auto 0px;
   text-align: center;
  }
  
  input[type="text"] {
   width: 360px;
   height: 50px;
   border: none;
   background: #fff;
   border-radius: 10px;
   margin: 5px auto;
   padding-left: 10px;
   color: #745A74;
   font-size: 15px;
  }
  
  input[type="checkbox"] {
   float: left;
   margin: 5px 0px 0px;
  }
  
  span {
   float: left;
  }
  
  .botton {
   width: 130px;
   height: 40px;
   background: #745A74;
   border-radius: 10px;
   text-align: center;
   color: #fff;
   margin-top: 30px;
   line-height: 40px;
  }
 </style>
</head>
<body>
<div class="login">
 <form action="login.php" method="post">
  <img src="images/header.png"><br>
  <input type="text" name="username" placeholder="请输入用户名!" value=""><br>
  <input type="text" name="password" placeholder="请输入密码!" value=""><br>
  <input type="submit" class="botton" value="login">
 </form>
 <div class="clear"></div>
</div>
</body>
  
</html>

接着把前端登录信息发送到后端,再去数据库进行验证。这一步的前提是我们可以连接好数据库,db.php。

<?php
  
$dbName = 'demo';
$host = '127.0.0.1';
$user = 'root';
$password = '123456';
  
$dsn = "mysql:host=$host;dbname=$dbName";
$pdo = new PDO($dsn, $user, $password);
  
function sql($table, $field = '*', $where = '')
{
 global $pdo;
 $sql = 'select' . ' ' . $field . ' ' . 'from' . ' ' . $table . ' where ' . $where;
 $data = $pdo->query($sql)->fetch();
 return $data;
}

  这里连接数据库采用实例化pdo对象的方法,此外还封装了一个sql方法,方便执行SQL查询。接着处理前端传来的数据,进行用户信息验证,login.php。

<?php
session_start();
include "db.php";
@$name = $_POST['username'];
@$pas = $_POST['password'];
  
$row = sql('user', '*', "username = '$name'");
if (!$row) {
 return "用户名不存在!请检查用户名~~";
}
  
if ($row['password'] == $pas) {
 $_SESSION['username'] = "$name";
 echo "<script>
 alert('登录成功!正在跳转...')
</script>";
 echo "<a href='index.php'>如果跳转失败请点击跳转~~</a>";
 header("Refresh:1;url=index.php");
}

  验证失败会发出提醒,验证成功之后跳转到登陆成功页面,index.php。

<?php
echo "<h1>这里是主页</h1>";
session_start();
$name = $_SESSION['username'];
if ($name) {
 echo "<script>
  alert(\"尊敬的$name ,欢迎回来!!\");
</script>";
}else{
 echo "<script>
 alert('您还尚未登录!请返回登录~~')
</script>";
 echo "<a href='index.php'>如果跳转失败请点击跳转~~</a>";
 header("Refresh:1;url=login.html");
}

  这样就简单实现了一个利用前后端数据库交互,session的登陆验证,希望可以帮到大家,谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值