加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

利用会话控制实现页面登录与注销功能(高颜值许愿墙实例源码)

发布时间:2020-12-12 02:15:26 所属栏目:MySql教程 来源:网络整理
导读:首先是一个普通的登陆页面实现 登录页面login.php ! DOCTYPE html html head title 登陆页 / link rel ="stylesheet" href ="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity ="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt2

首先是一个普通的登陆页面实现

登录页面login.php

<!DOCTYPE html>
<html>
    head>
        title>登陆页</link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"bodydiv class="container">
            ="card col-12 mt-5">
                ="card-body">
                    h4 ="card-title">
                        用户登录
                    h4="col-12 mt-4 d-flex justify-content-center">
                        form ="col-8" method="post" action="action.php">
                            input type="hidden" name="action" value="login"="form-group">
                                label for="username">用户名label="text"
                                       class="form-control"
                                       id="username"
                                       name
                                       placeholder="请输入用户名"div="password">密码="password"="请输入密码"="form-group form-check"="checkbox"="form-check-input"="remember"="remember"="form-check-label"
                                       for
                                    在这台电脑上记住我的登录状态
                                button ="submit"
                                    class="btn btn-primary"
                                登录
                            buttonform>

登录功能实现action.php

    <?php
    session_start();

    switch ($_REQUEST['action']) {
        case 'login':
            $username = $_POST['username'];
            $password = $_POST['password'$remember = $_POST['remember'];

            $user = getUser();

            if ($username != $user['username']) {
                // 登录失败
                sendLoginFailedResponse();
            }

            $password != $user['password'$remember) {
                rememberLogin($username);
            }

            $_SESSION['username'] = ;
            header("location:index.php");

            break;

        case 'logout':
            session_unset();
            setcookie("username","",time() - 1);
            header("location:login.php";
    }


    function getUser() {
        return array(
            "username" => "cyy","password" => "123456"
        );
    }

     sendLoginFailedResponse() {
        $response = "<script>
    alert('用户名或密码错误!');
    window.location='login.php';
    </script>";
        echo $responsedie;
    }

    function rememberLogin() {
        $username,1)">time() + 7 * 24 * 3600);
    }

首页index.php

    <?php
    session_start();

    if (rememberedLogin()) {
        $_SESSION['username'] = $_COOKIE['username'];
    }

    if (!hasLoggedIn()) {
        header("location:login.php");
        die;
    }

    function hasLoggedIn() {
        return isset($_SESSION['username']) && validateUsername($_SESSION['username']);
    }

    function validateUsername($username) {
        return $username == "cyy";
    }

    function rememberedLogin() {
        return isset($_COOKIE['username']) && validateUsername($_COOKIE['username']);
    }
    ?>

    >主页nav ="navbar navbar-light bg-light"a ="navbar-brand"
                        使用 Cookie 和 Session 实现会话控制
                    ahref="action.php?action=logout"="btn btn-outline-danger my-2 my-sm-0"
                                type="button"
                            注销
                        nav="d-flex justify-content-around mt-5"="card col-5"h5 
                                会话控制实战内容一
                            h5h6 ="card-subtitle mb-2 text-muted"
                                SESSION 部分
                            h6p ="card-text"
                                实现用户认证功能,用户登录、退出与身份识别
                            p
                                会话控制实战内容二
                            
                                COOKIE 部分
                            
                                实现登录记住用户功能,七天免登录认证
                            ="d-flex justify-content-around mt-4">

接下来是会话控制实例:许愿墙源码

许愿墙首页index.php

    DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"meta http-equiv="Content-Type" content="text/html;charset=UTF-8">许愿墙="Css/index.css" />
        script ="text/javascript" src='Js/jquery-1.7.2.min.js'></script='Js/index.js'id='top'="wish.php"><span ='send'span='main'php
            //连接数据库
            $connection=mysqli_connect('127.0.0.1','root','123456');
            if(mysqli_connect_error()){
                die(mysqli_connect_error());
            }
            mysqli_select_db($connection,'wall');
            mysqli_set_charset($connection,'utf8');
            $sql="SELECT * FROM wall";
            $result=mysqli_query($connection,$sql);
            //显示留言
            while($row=mysqli_fetch_assoc($result)){
                $wish_time=$row['wish_time'];
                $time=date('Y-m-d H:i:s',$wish_time);
                $id=$row['id'];
                //判断留言板颜色
                switch($row['color']){
                    case 'a1':
                        echo "<dl class='paper a1'>";
                        break;
                    case 'a2':
                        echo "<dl class='paper a2'>";
                        break;
                    case 'a3':
                        echo "<dl class='paper a3'>";
                        break;
                    case 'a4':
                        echo "<dl class='paper a4'>";
                        break;
                    case 'a5':
                        echo "<dl class='paper a5'>";
                        break;
                    default:
                        echo "<dl class='paper a1'>";
                        break;
                }
                echo "<dt>";
                echo "<span class='username'>{$row['name']}</span>";
                echo "<span class='num'>No.{$row['id']}</span>";
                echo "</dt>";
                echo "<dd class='content'>{$row['content']}</dd>";
                echo "<dd class='bottom'>";
                echo "<span class='time'>{$time}</span>";
                echo "<a href="delete.php?num={$id}" class='close'></a>";
                echo "</dd>";
                echo "</dl>";
            }
            mysqli_close($connection);
            ?>
        >
        
    <!--[if IE 6]>
        <script type="text/javascript" src="./Js/iepng.js"></script>
        <script type="text/javascript">
            DD_belatedPNG.fix('#send,#close,.close','background');
        </script>
    <![endif]-->
    >

添加愿望页面wish.php

    DOCTYPE  style ="text/css">
            #content {
                width: 638px;
                height650px
                margin0 auto
                margin-top100px;
                /*background-color:#F0FAFF;
                border:2px solid #C9F;*/
            }
            #content .c-top 80px
                background url(./Images/content_top.jpg) no-repeat;
            
            #content .c-bottom 50px url(./Images/content_bottom.jpg) no-repeat
            .c-content 470px url(./Images/content_bg.jpg) repeat
            .papercolor588px 60px
                margin-left 35px
                padding-top15px
            .p-left
                float left 120px
                line-height 27pxp-left
            .p-right;            
            
            .color330 20px
                border-right #404040 1px solid 
                border-top  
                border-left#404040 1px solid 25px
                cursor pointer
                border-bottom
            .papercontent 588px 210px
            .left 294px
            .right
            .left-top
                margin-bottom 10px
            .left-bottom{

            
            .right-top
            .right-bottom200px150px
                border 1px solid orange20px
                background-color#E8DEFF
            .name
                clear both10px
            .name-left60px 26px
            .name-right
            .name-right input 200px
            .code
            .code-left50px
            .code-content
            .code-content input 100px
            .code-rightleft
            .code-right input 40px pink
            .submit174px38px url(./Images/pic_submit.gif) no-repeat217px
            .shuname80px25px
            span
                font-size 13px
                font-family "微软雅黑"}
        style="content"="c-top"action="add.php" id="myfrom"="c-content"="papercolor"="p-left">请选择纸条颜色:="p-right"="color330"="a1" style="background:#FFDFFF">
                              ="a2"="background:#C3FEC0"="a3"="background:#FFE3b8"="a4"="background:#CEECFF">
                             ="a5"="background:#E8DEFF"=""="idvalue"="idvalue">                   
                        ="papercontent"="left"="left-top">输入你的祝福纸条内容:="left-bottom"textarea cols="25" rows="8"="textfont"="textfont"textarea="right"="right-top">纸条效果预览:="right-bottom"="height:15px">第x条br/></>
                                 ="height:100px;margin-top:10px"="font"="shuname"="name">署名:>            
                            ="name-left">您的署名:="name-right"="nameright" type="name"=""="code"="code-left">验证码:="code-content"="codeone"="recode"="code-right"="codetwo"="code"="<?php echo mt_rand(1000,9999); ?>" readonly>                
                    <div class="submit"><button type="submit" style="width:174px;height:38px"></button></div>-->
                    ="BORDER-RIGHT: #f33b78 1px outset; BORDER-TOP: #f33b78 1px outset; FONT-WEIGHT: bold; BORDER-LEFT: #f33b78 1px outset; COLOR: #ffffff; BORDER-BOTTOM: #f33b78 1px outset; BACKGROUND-COLOR: #70ae0b;margin-left: 225px"="→ 开始贴许愿小纸条 ←"="submit">
                    
                        ="index.php"="input"="button"="Submit2"="返回">    
                hr/ style="color:orange;width:550"="c-bottom"-->
        ="text/javascript">
            //改变颜色
            $(".color330).click(function(){            
                var value=$(this).css(background-color);
                 idvalue).attr(id);
                console.log(idvalue);
                $(#idvaluevalue,idvalue);
                $(.right-bottom改变值触发的事件
             textfont  document.getElementById('textfont);
             font font);
            textfont.onchange(){
                font.innerHTMLtextfont.value;            
            }

             nameright nameright);
            nameright.onchange(){
                document.getElementById(name).innerText署名: +nameright.value;    
            }
            
            在填写完毕验证码之后验证是否一致
             codeone codeone codetwo codetwo表单时区焦点事件
            codeone.onblur(){
                验证两次验证码是否一致
                if(codeone.value != codetwo.value){
                    .nextSibling.innerHTML验证码不一致!'
                    .nextSibling.style.colorred;
                }
            }

            $( #submit ).click(  () {
                window.location.hrefadd.php; 
            } );
                
        >

新增愿望实现add.php

    <?php

     获取表单提交数据
    $name=$_POST['name'];
    $textfont=$_POST['textfont'$wish_time=time();
    $color=$_POST['idvalue'];

     数据库操作
    $connection=mysqli_connect('127.0.0.1','123456');
    if(mysqli_connect_error()){
        die(());
    }
    mysqli_select_db($connection,'wall');
    mysqli_set_charset();
    $sql="INSERT INTO wall(content,name,wish_time,color) VALUES('$textfont','$name',1)">$wish_time,1)">$color')";
    $result=mysqli_query($sqlif($result){
        echo '<script>alert("发布成功!");document.location = "index.php";</script>';
    }else{
        echo '<script>alert("发布失败!");document.location = "index.php";</script>';
    }
    mysqli_close($connection);

    ?>

删除愿望delete.php

    <?接受要删除的留言id
    $num=$_GET['num'$sql="DELETE FROM wall WHERE id=$num"echo '<script>alert("删除成功!");document.location = "index.php";</script>';

    }echo '<script>alert("删除失败!");document.location = "index.php";</script>');

    ?>

附上数据库结构wall.sql

-- phpMyAdmin SQL Dump
-- version 4.8.5 https://www.phpmyadmin.net/
--
-- 主机: localhost 生成日期: 2019-08-18 22:08:38 服务器版本: 8.0.12 PHP 版本: 7.3.4

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS !40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION !40101 SET NAMES utf8mb4 ;

--
-- 数据库: `wall`
--

 --------------------------------------------------------

 表的结构 `wall`CREATE TABLE `wall` (
  `id` tinyint(4) NOT NULL COMMENT '留言编号'varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci 留言内容20) NULL DEFAULT 匿名的宝宝' COMMENT 署名int(11) 留言时间char(2) 留言背景色
) ENGINE=InnoDB DEFAULT CHARSETutf8;

 转存表中的数据 `wall`INSERT INTO `wall` (`id`,`content`,`name`,`wish_time`,`color`) VALUES
(17,111',1); font-weight: bold">1566136880,1)">a1),(19,1)">3331566136894,1)">a321,1)">5551566136911,1)">a524,1)">99991566137235,1)">a4);

 转储表的索引 表的索引 `wall`
--
ALTER  `wall`
  ADD PRIMARY KEY (`id`);

 在导出的表使用AUTO_INCREMENT 使用表AUTO_INCREMENT `wall` `wall`
  MODIFY `id` NULL AUTO_INCREMENT COMMENT =26COMMIT!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT !40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS !40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

?

知识点补充:

【使用 COOKIE 实现会话控制】
用于存储用户关键信息
保存在客户端(浏览器)
通过 HTTP 请求/响应头传输

【COOKIE 失效】
COOKIE过期
用户手动删除 COOKIE
服务器清除 COOKIE 的有效性


?

【使用 SESSION 实现会话控制】
用于存储用户相关信息
保存在服务端
通过保存在客户端的 SESSION ID 来定位 SESSION 内容

【SESSION 失效/清除】
COOKIE过期(关闭浏览器)
用户手动删除 COOKIE
服务端删除 SESSION 文件或清空 SESSION 内容

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读