PHP学习笔记——用户登录使用cookie

前端页面index.php

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登陆</title>
    </head>
    <body>
        <div align="center">
        <form name="login" action="index.php" method="post">
                <p>用户名<input type=text name="name"></p>
                <p>密 码<input type=password name="password"></p>
                <p><input type="submit" name="submit" value="登录"> 
                </p>
            </form>
<?php
$name = $_POST["name"];
$password = $_POST["password"];
if(isset($name) && isset($password)){  
    setcookie("name","$name",time()+3600);
    setcookie("password","$password",time()+3600);
    header("refresh:0;url=success.php");
}
?>
            </div>
    </body>
</html>

后端判断success.php

<?php
if (!isset($_COOKIE["name"]) || !isset($_COOKIE["password"])) {
    echo('账号密码不能为空');
    header("refresh:1;url=index.php");
}
elseif ($_COOKIE["name"]!='xiaowang'||$_COOKIE["password"]!='wangmima') {
    echo '账号密码不正确';
    header("refresh:1;url=index.php");
}
else{
    echo "登录成功";
    echo '<a href="logout.php"><input type="submit" name="submit" value="注销"></a>';
}
?>

当用户没有输入账号密码时,将会显示账号密码不能为空,且1秒后返回登录页面

同理,账号不为xiaowang,密码不为wangmima时返回账号密码

输入成功时跳转到成功页面

注销页面logout.php

<?php  
if (isset($_COOKIE["name"]) || isset($_COOKIE["password"])) {
    setcookie("name", "", time()-3600);
    setcookie("password", "", time()-3600);
    echo '<span id="seconds">3</span>秒后返回到首页
<script type="text/javascript">
    
    // 获取秒数显示id
    var seconds = document.getElementById("seconds");
    // 设置秒数
    var num = 3;
    var timer = setInterval(function () {
        num--;
        seconds.innerText = num;
        if(num == 0){
            window.location = "index.php";
        }
    },1000)
</script>';
}
else{
    echo '未登录';
    echo '<br>';
     echo '<span id="seconds">3</span>秒后返回到首页

<script type="text/javascript">
    
    // 获取秒数显示id
    var seconds = document.getElementById("seconds");
    // 设置秒数
    var num = 3;
    var timer = setInterval(function () {
        num--;
        seconds.innerText = num;
        if(num == 0){
            window.location = "index.php";
        }
    },1000)
</script>';
}

   

?>

当页面存在cookie时,设置时效为当前时间减一小时,即cookie过期。

不存在cookie时,3秒后将会跳转到登录页面

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页