基于Cookie的简单登录流程

1 登录页面:login.php

<?php
//判断一下是否有cookie
if (isset($_COOKIE['user']) && $_COOKIE['user']==='admin') {
    echo '您已经登录';
    echo "<a href='logout.php'>注销登录</a>";
    exit();
}
//登录逻辑
if (isset($_POST['submit'])) {
    //判断用户名和密码是否正确
    if ( isset($_POST['user']) && isset($_POST['pwd']) && $_POST['user']==='admin' && $_POST['pwd'] === 'admin') {
        //写入cookie
        if (setcookie('user',$_POST['user'],time()+3600)) {
            //设置cookie成功 跳转到首页
            header('Location:skip.php?url=index.php&info=000登录成功');

        } else {
            echo 'cookie设置失败';
        }
    } else {
        header('Location:skip.php?url=index.php&info=登录失败');
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<form method="post" action="login.php">
    姓名:<input type="text" name="user"/>
    密码:<input type="password" name="pwd" />
    <input type="submit" name="submit" value="登录">
</form>
</body>
</html>

2  首页  index.php

<?php
if (isset($_COOKIE['user']) && $_COOKIE['user'] === 'admin') {
    echo "亲爱的{$_COOKIE['user']}你好,欢迎回来";
    echo "<br><a href='logout.php'>注销登录</a>";
} else {
    echo "<a href='login.php'>请登录</a>";
}

3  跳转中转页 skip.php

<?php
//跳转中转页
if (!isset($_GET['url']) || !isset($_GET['info'])) {
    exit('url 或 info 没有收到');
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>桥页</title>
    <meta http-equiv="refresh" content="3;url=<?php echo $_GET['url'] ?>">
</head>
<body>
    <div style="text-align:center;font-size:20px;"><?php echo $_GET['info'] ?>,3秒后自动跳转!</div>
</body>
</html>

4  注销登录 logout.php

<?php
//如果cookie存在 我们进行删除
if (isset($_COOKIE['user']) && $_COOKIE['user'] === 'admin') {
    //删除cookie操作
    if (setcookie('user',$_POST['user'],time()+3600)) {
        //跳转到登录页
        header('Location:login.php');
    } else {
        echo '删除失败 请重试';
    }
}

 

posted @ 2020-11-10 16:19  棉花糖88  阅读(1452)  评论(0编辑  收藏  举报