年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 2108|回复: 0

Cookie使用的一个小实例

[复制链接]
  • TA的每日心情

    2024-10-15 10:05
  • 签到天数: 372 天

    [LV.9]以坛为家II

    发表于 2016-1-19 22:55:44 | 显示全部楼层 |阅读模式
    本帖最后由 Sian 于 2016-1-19 22:59 编辑

    1、先看效果

    屏幕快照 2016-01-19 下午10.56.35.png
    屏幕快照 2016-01-19 下午10.57.05.png
    屏幕快照 2016-01-19 下午10.57.29.png

    2、几个页面
    A、cookie.php   B、login.php   C、logout.php   D、index.php

    3、部分代码
    cookie.php
    [PHP] 纯文本查看 复制代码
    <?php
    header('Content-Type:text/html;charset:utf-8');
    if (!(isset($_COOKIE['isLogin']) && $_COOKIE['isLogin'] == 1)){
    echo "请先登录<br/>";
    echo '<script>setTimeout(\'location="login.php"\', 3000);</script>';
    }
    login.php
    [PHP] 纯文本查看 复制代码
    <?php
    if(isset($_POST['dosubmit'])){
    $pdo = new PDO("mysql:host=localhost;dbname=think", "root", "*****");
    $statement = $pdo->prepare("select id, username, allow_1, allow_2, allow_3 from user where username = ? and password = ?");
    $statement->execute(array($_POST['username'], md5($_POST['password'])));
    
    if ($result = $statement->fetch(PDO::FETCH_ASSOC)){
    $time = time()+24*60*60;
    setcookie("uid", $result['id'], $time);
    setcookie("username", $result['username'], $time);
    setcookie("allow_1", $result['allow_1'], $time);
    setcookie("allow_2", $result['allow_2'], $time);
    setcookie("allow_3", $result['allow_3'], $time);
    setcookie("isLogin", "1", $time);
    
    header("Location:index.php");
    }else{
    echo "登录失败!<br/>";
    }
    }        
    ?>
    <h3>用户登录</h3>
    <form action="" method="post">
    username:<input type="text" name="username" value=""/><br/>
    password:<input type="password" name="password" value="" /><br/>
    
    <input type="submit" name="dosubmit" value="登录" /><br/>
    </form>
    
    
    index.php
    [PHP] 纯文本查看 复制代码
    <?php
    include 'cookie.php';
    
    echo "{$_COOKIE['username']}你好!欢迎来到首页!, <a href='logout.php'>退出</a><br/>";
    if (isset($_COOKIE['allow_1']) && $_COOKIE['allow_1'] == 1) echo "你有1的权限<br/>";
    if (isset($_COOKIE['allow_2']) && $_COOKIE['allow_2'] == 1) echo "你有2的权限<br/>";
    if (isset($_COOKIE['allow_3']) && $_COOKIE['allow_3'] == 1) echo "你有3的权限<br/>";
    logout.php
    [PHP] 纯文本查看 复制代码
    <?php
    $username = $_COOKIE['username'];
    
    setcookie("id", "", time()-3600, "/");
    setcookie("username", "", time()-3600, "/");
    setcookie("allow_1", "", time()-3600, "/");
    setcookie("allow_2", "", time()-3600, "/");
    setcookie("allow_3", "", time()-3600, "/");
    setcookie("isLogin", "", time()-3600, "/");
    
    echo "再见!{$username}";
    
    echo '<script>setTimeout(\'location="login.php"\', 3000);</script>';
    

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-12-5 03:10 , Processed in 0.056420 second(s), 22 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表