使用php登录页面中的setcookie问题

问题描述 投票:-2回答:1

我正在尝试通过使用cookie使用PHP创建一个小的登录页面。我在phpMyAdmin中有一个链接到它的数据库/表。一切看起来都不错,但是当我自己尝试页面并输入用户名/密码时,我确实会进入管理页面(否则,我会收到“哎呀,好像您错了”的消息),但错误消息告诉了我我尚未登录。这似乎是什么问题?感觉就像它就在我面前,却看不见它。

我的带有索引,管理和数据库页面的代码:

<?php
//log in
if (isset($_POST["log"]) && $_POST["log"] == "1") {
    $_POST["log"] = 0;
    $identifiant = htmlentities ($_POST["username"]);
    $password = htmlentities ($_POST["passwd"]);
    $encryp_pwd = hash("sha256", $password);

    require_once("database.php");

    $sql = "SELECT * FROM MyTable WHERE User='$identifiant' AND Passwd='$encryp_pwd'; ";
    $result = $connexion->query($sql) or die ("Oops, something went wrong");


    if(mysqli_num_rows ($result) == 1){
        //set cookie and a time
        setcookie('logged_in', $identifiant, time()+60*60*24);
        header("location: admin.php");

    }
    else
        echo "<h2>Seems like you got it wrong</h2> <a href='index.php'>try again</a>";
}
else { 
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>Welcome</h1>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="identifiant" /> <br/>
        <input type="text" name="passwd" placeholder="Password" /> <br/>
        <input type="submit" value="log in" />
        <input type="hidden" name="log" value="1" />
    </form> 
</body>
</html>
<?php
}
?>

下面的管理员


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <h1>Admin</h1>

    <?php

        //check if there is a cookie and if the person is logged in
        if (isset($_COOKIE['logged_in'])) {
            echo "<h2>You are logged in as: " . $_COOKIE['logged_in'] . "</h2>";
            echo "<a href='logout.php'>Click here to log out</a>";
        }
        //Message + link to the log in page if not
        else {
            echo "<p>You are not logged in</p>";
            echo "<a href='index.php'>Click here to log in</a>";
        }

    ?>    

</body>
</html>


下面的数据库



<?php 
    $serveur = "localhost";
    $user = "xxxx";
    $motdepass = "xxxx";
    $base = "xxxx";

    $connexion = new mysqli($serveur, $user, $motdepass, $base);


?>



php cookies
1个回答
0
投票

我页面中的每次都相同,需要更改。很简单的错误。

© www.soinside.com 2019 - 2024. All rights reserved.