通过今天的学习,我懂得了cookie和session两种会话使用,并且同session和cookie完成登入验证,以下是我的编程代码:
pdo+cookie 方式
1,链接数据库类 配置 config.php
实例
<meta charset="UTF-8"> <?php /** * Created by PhpStorm. * User: admin * Date: 2018/9/1 * Time: 21:07 */ class config { public function config() { $data=[ 'db_host'=>'mysql:host=127.0.0.1;dbname=test', 'db_user'=>'root', 'db_password'=>'root', 'db_charset'=>'utf8' ]; return $data; } }
点击 "运行实例" 按钮查看在线实例
2,链接数据库 connec.php
实例
<?php /** * Created by PhpStorm. * User: admin * Date: 2018/9/1 * Time: 20:53 */ require 'config.php'; class connection { public function connec() { $result=new config(); $data= $result->config(); $pdo=''; try{ $opts_values = array(PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8'); $pdo=new PDO($data['db_host'],$data['db_user'],$data['db_password'],$opts_values); }catch (PDOException $e) { $pdo= die('数据库链接异常'.$e->getMessage()); } return $pdo; } }
点击 "运行实例" 按钮查看在线实例
3,首页 index.php
实例
<?php $page_title='首页'; //引入页面头部 include 'inc/header.php'; echo '<h2>我是首页</h2>'; if (isset($_COOKIE['id'])&& basename($_SERVER['PHP_SELF'])!='loginout.php') { echo '<a href="loginout.php">退出</a>'; }else { echo '<a href="login.php"> 登入</a>'; } //导入页面的底部 include 'inc/footer.php';
运行实例 »
点击 "运行实例" 按钮查看在线实例
4,登入页面 login_page.php
实例
<?php $page_title = '用户登录'; include 'inc/header.php'; ////错误 信息显示 if (isset($errors) && !empty($errors)) { $errors_msg = '<p style="color:red">'; foreach ($errors as $msg) { $errors_msg .= $msg .'<br>'; } echo $errors_msg .'</p>'; } ?> <h2 style="color:red">用户登录</h2> <form action="login.php" method="post"> <p> <label for="email">邮箱:</label> <input type="email" name="email" id="email" value="<?php echo isset($_POST['email'])?$_POST['email']:'' ?>"> </p> <p> <label for="password">密码:</label> <input type="password" name="password" id="password" value="<?php echo isset($_POST['password'])?$_POST['password']:'' ?>"> </p> <p> <button type="submit" name="submit" id="submit">登录</button> <a href="regiser.php">注册</a> </p> </form> <?php include 'inc/footer.php'?>
点击 "运行实例" 按钮查看在线实例
5,登入逻辑页面 login.php
实例
<?php if ($_SERVER['REQUEST_METHOD']='POST') { //加载公用函数 include 'inc/validate.php'; list($bool,$data)= check_login(isset($_POST['email'])?$_POST['email']:'',isset($_POST['password'])?$_POST['password']:''); if ($bool) { //设置cookie setcookie('id',$data['id']); setcookie('name',$data['name']); redirect_user('loginin.php'); }else { $errors=$data; } //关闭数据库联系 // var_dump($result); //加载公共函数 } include 'login_page.php';
点击 "运行实例" 按钮查看在线实例
6.登入成功页面
实例
<?php $page_title='首页'; //引入页面头部 include 'inc/header.php'; if (!isset($_COOKIE['id'])) { require 'inc/validate.php'; redirect_user(); } echo <<<"WELCOME" <h2 style="color: pink">登入成功</h2> <p>欢迎您:{$_COOKIE['name']}</p> <a href="loginout.php">退出</a> WELCOME; //导入页面的底部 include 'inc/footer.php';
运行实例 »
点击 "运行实例" 按钮查看在线实例
7.退出页面 loginout.php
实例
<?php //启动会话 session_start(); //登录成功页面 //判断用户是否登录? if (!isset($_SESSION['id'])) { require 'inc/function.php'; redirect_user(); }else { // set_session('name','',time()-3600); // set_session('id','',time()-3600); session_destroy(); setcookie('PHPSESSID',time()-3600); } $page_title = '退出成功'; //导入页面的公共头部 include 'inc/header.php'; //heredoc echo <<< "WELCOME" <h2 style="color:red">退出成功</h2> <p><a href="login.php">登入</a></p> WELCOME; //导入页面的公共底部 include 'inc/footer.php';
点击 "运行实例" 按钮查看在线实例
8,验证邮箱密码是否正确 函数类
实例
<?php require 'connection.php'; //默认的url ////$url='http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); //$url='http://'.$_SERVER['HTTP_HOST'].dirname(__FILE__); //var_dump($url); //登入成功的跳转 function redirect_user($page='index.php') { //默认的url $url='http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); //如果有\去掉右边的/\\ $url=rtrim($url,'/\\'); //将地址拼接 $url.='/'.$page; header('Location:' .$url); exit(); } function check_login($email,$pass) { //保存错误信息 $errors=[]; //非空验证 if (empty($email)) { $errors='邮箱不能为空!'; }else { $e=htmlspecialchars(trim($email)); } if (empty($pass)) { $errors='邮箱不能为空!'; }else { $p=htmlspecialchars(trim($pass)); } //到表中验证 if(empty($errors)) { //根据邮箱和密码进行验证 //创建sql语句 $sql="select * FROM `show` where email=:email and `password`=:password"; //实力化链接对象 $pd=new connection(); //创建预定编译 $stmt= $pd->connec()->prepare($sql); $stmt->execute(['email'=>$e,'password'=>sha1($p)]); $row=$stmt->fetch(PDO::FETCH_ASSOC); if ($row!=false) { return [true,$row]; }else { $errors[]='邮箱或密码输入错误,请检查!'; } return [false,$errors]; } }
点击 "运行实例" 按钮查看在线实例
mysqli+session方式
1,数据库链接
实例
<?php $dbc=mysqli_connect('127.0.0.1','root','root','test'); //判断是否连接成功 if(mysqli_connect_errno()) { die('连接失败'.mysqli_connect_error()); }
运行实例 »
点击 "运行实例" 按钮查看在线实例
2,验证登入函数类
实例
<?php function redirect_user($page='index.php') { //默认的url地图 $url='http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); //去除右边的符号 $url=rtrim($url,'/\\'); //将链接拼接起来 $url .='/'.$page; //跳转 header('location:'.$url); exit(); } function check_login($dbc,$email,$pass) { $errors=[]; if (empty($email)) { $errors='邮箱不能为空'; }else { $e= mysqli_real_escape_string($dbc,trim($email)); } if (empty($pass)) { $errors='密码不能为空'; }else { $p=mysqli_real_escape_string($dbc,trim($pass)); } if (empty($errors)) { //判断密码或邮箱是否正确 $sql="select id,name from `show` where `email`='$e' and `password`= sha1('$p') "; //执行查询 $res=mysqli_query($dbc,$sql); if (mysqli_num_rows($res)==1) { $row=mysqli_fetch_array($res,MYSQLI_ASSOC); return [true,$row]; }else { $errors[]='邮箱或密码不正确'; } return [false,$errors]; } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
3,头部页面 header.php
实例
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> <?php echo isset($page_title)?$page_title:'未知页面'; ?> </title> </head> <body> <h2>weclome to my home!</h2>
运行实例 »
点击 "运行实例" 按钮查看在线实例
4,底部页面footer.php
5,首页 index.php
实例
<?php /** * Created by PhpStorm. * User: admin * Date: 2018/9/2 * Time: 9:33 */ session_start(); //引入页面头部 include 'inc/header.php'; echo '<h2>我是首页</h2>'; if (isset($_SESSION['id']) && basename(__FILE__)!='loginout.php') { echo "<a href='logout.php'>退出:亲爱的:{$_SESSION['name']}</a>"; }else { echo '<a href="login.php"> 登入</a>'; } //导入页面的底部 include 'inc/footer.php';
运行实例 »
点击 "运行实例" 按钮查看在线实例
6,登入页面
实例
<?php $page_title = '用户登录'; include 'inc/header.php'; ////错误 信息显示 if (isset($errors) && !empty($errors)) { $errors_msg = '<p style="color:red">'; foreach ($errors as $msg) { $errors_msg .= $msg .'<br>'; } echo $errors_msg .'</p>'; } ?> <h2 style="color:red">用户登录</h2> <form action="login.php" method="post"> <p> <label for="email">邮箱:</label> <input type="email" name="email" id="email" value="<?php echo isset($_POST['email'])?$_POST['email']:'' ?>"> </p> <p> <label for="password">密码:</label> <input type="password" name="password" id="password" value="<?php echo isset($_POST['password'])?$_POST['password']:'' ?>"> </p> <p> <button type="submit" name="submit" id="submit">登录</button> <a href="regiser.php">注册</a> </p> </form> <?php include 'inc/footer.php'?>
运行实例 »
点击 "运行实例" 按钮查看在线实例
7,登入逻辑页面
实例
<?php /** * Created by PhpStorm. * User: admin * Date: 2018/9/2 * Time: 9:37 */ //启动会话 session_start(); if ($_SERVER['REQUEST_METHOD']='POST') { //引入验证函数 include 'inc/validate.php'; //连接数据库 require 'inc/connect.php'; list($check,$data)=check_login($dbc,isset($_POST['email'])?$_POST['email']:'',isset($_POST['password'])?$_POST['password']:''); if ($check) { $_SESSION['id']=$data['id']; $_SESSION['name']=$data['name']; //跳转 redirect_user('loggedin.php'); }else { $errors = $data; } mysqli_close($dbc); } include 'login_page.php';
点击 "运行实例" 按钮查看在线实例
8,登入成功页面
实例
<?php //启动会话 session_start(); //登录成功页面 //判断用户是否登录? if (!isset($_SESSION['id'])) { require 'inc/function.php'; redirect_user(); } $page_title = '登录成功'; //导入页面的公共头部 include 'inc/header.php'; //heredoc echo <<< "WELCOME" <h2 style="color:red">登录成功</h2> <p>欢迎您: 亲爱的 {$_SESSION['name']}</p> <p><a href="logout.php">退出</a></p> WELCOME; //导入页面的公共底部 include 'inc/footer.php';
运行实例 »
点击 "运行实例" 按钮查看在线实例
9,退出页面
实例
<?php //启动会话 session_start(); //登录成功页面 //判断用户是否登录? if (!isset($_SESSION['id'])) { require 'inc/function.php'; redirect_user(); }else { // set_session('name','',time()-3600); // set_session('id','',time()-3600); session_destroy(); setcookie('PHPSESSID',time()-3600); } $page_title = '退出成功'; //导入页面的公共头部 include 'inc/header.php'; //heredoc echo <<< "WELCOME" <h2 style="color:red">退出成功</h2> <p><a href="login.php">登入</a></p> WELCOME; //导入页面的公共底部 include 'inc/footer.php';
点击 "运行实例" 按钮查看在线实例
ps:两者头部,尾部一样
手操图片
总结:
cookie 是客 户端 存贮数据,而session是服务器端存贮数据
cookie 通过cookie[]创建 通过setcookie[参数,‘’time()-3600] 销毁
session 通过 $_SESSION[]创建,通过session_destroy();销毁服务器端 通过
setcookie('PHPSESSID',time()-3600);销毁客 户端