使用php会话和cookie重定向浏览器错误[header]

时间:2016-10-21 11:35:41

标签: php session redirect cookies

成功后我的标题重定向出现了一个奇怪的问题password_verify()这是login.php的一部分

的login.php

            $sql = "SELECT * FROM formular WHERE email='".$emailUsername."' OR username='".$emailUsername."'";
            $result = $conn->query($sql);
            $row = $result->fetch_assoc();

            if (password_verify($password, $row["hash"])) {
                if (isset($_POST["remember_me"])) {

                    $_SESSION["remember_me"] = $emailUsername;

                    setcookie('remember_me', md5($emailUsername . time()));
                    $stmt = $conn->prepare("INSERT INTO sessions (id) VALUES (?)");
                    $stmt->bind_param("s", $_COOKIE["remember_me"]);
                    $stmt->execute();

                    if ($stmt->affected_rows) {

                    }

                    $stmt->close();
                    $conn->close();
                }
                $_SESSION = array(
                        "login" => true,
                        "data" => array(
                                "username" => $row["username"],
                                "email" => $row["email"],
                                "time" => time() +10*5
                        )
                );
                header('Location: ../home/userarea.php');
                exit();
            }
            else {
                $errorField2 = "<div class=\"alert alert-danger\">".
                    "<strong>Whoops!</strong> Wrong entries!".
                    "</div>";
            }

现在位于每个页面的顶部,我有一个文件,用于检查会话是否已设置,然后将用户重定向到该页面。并且在登录页面上我有一个 remember_me复选框,应该在成功输入后设置 cookie ,这样用户就不必再次登录并将其自动重定向到userarea。 PHP。

在我的情况下,任何用户都可以看到userarea.php

bootstrap.php中

ob_start();
if (isset($_SESSION["login"])) {
    if ($_SESSION["data"]["time"] >= time()) {
        if(isset($_COOKIE["remember_me"])) {
            header('Location: ../home/userarea.php');
            exit();
        }
    } else {
            header('Location: ../log_reg/login.php');
            exit();
    }

} else {

    //This line here is running my browser into the redirecting error "Page could not be loaded: The called website redirects the request so that it can never be terminated."

    #header('Location: ../log_reg/login.php');
    #exit();
}
ob_end_flush();

此文件应设置remember_me设置时的Cookie和session如果用户刚刚登录而未选中remember_me 允许在我的浏览器中设置Cookie,这样就不会出现问题了。

1 个答案:

答案 0 :(得分:1)

您的问题出在

isset($_SESSION["login"])

它处于无限循环中,因此重定向不会被执行:P
这是如何正确处理它:

ob_start();
if (isset($_SESSION["login"])) {
    if ($_SESSION["data"]["time"] >= time()) {
        if(isset($_COOKIE["remember_me"])) {
            header('Location: ../home/userarea.php');
            exit();
        }
    } else {
        header('Location: ../log_reg/login.php');
        exit();
    }

} else {
    if (basename($_SERVER["REQUEST_URI"]) == "login.php"){

    }
    else {
        header('Location: ../log_reg/login.php');
    }
}
ob_end_flush();