0

我在使用 PHP 和会话时遇到问题。这是我的dictionary.php 代码。

<?php
if(!isset($_SESSION['auth'])){
$_SESSION['auth'] = 0;
}
if($_SESSION['auth'] == 0){
header("Location: index.php");
}
?>

因此,有 index.php 应该将会话“auth”设置为 0 或 1:

<?php
    $msg = "";

//Password handler
if(!isset($_POST['password'])){
    $password = "";
}else{
    $password = $_POST['password'];
}

if(!isset($_SESSION['auth'])){
    $_SESSION['auth'] = 0;
}

//Username handler
if(!isset($_POST['username'])){
    $username = "";
}else{
       $username = $_POST['username'];
    if($username == "potato" && $password == "poteto"){
        $_SESSION['auth'] = 1;
        header("Location: dictionary.php");
    }else{
        $msg = "<br />
<font color=\"#FF0000\">Invalid username or password!</font><br />";
    }
}

if($_SESSION['auth'] == 0){
        header("Location: dictionary.php");
}

?>

(以上可能是不好的做法,但我只是为学校项目做这个,我不希望其他人看到文件 dictionary.php。)

index.php 使用带有 POST 方法的表单来发送$usernameand $password,以防万一您还没有注意到。

当我输入登录详细信息“potato”和“poteto”时,它会将我重定向到dictionary.php,但随后立即将我扔回index.php。我试过调整上面的代码,但没有运气。

如果有人需要我向他们展示这个,那么我可以提供一个 URL。

谢谢。

4

2 回答 2

2

如评论中所述,设置session_start()。还...

最后在 index.php 中重定向到 dictionary.php:

if($_SESSION['auth'] == 0){
        header("Location: dictionary.php");
}

在 dictionary.php 中,您重定向到 index.php 的相同条件:

if($_SESSION['auth'] == 0){
     header("Location: index.php");
}

因此,每当您的用户处于 的情况下$_SESSION['auth'] == 0,它都会导致无限重定向。你需要清理它。

于 2013-04-16T23:27:47.180 回答
0

你应该让你的重定向功能更舒服一点:

function site_redirect($location)
{
    $headers = true; // set to false to disable for troubleshooting

    $headers = $header && !headers_sent();
    if ($headers) {
        header("Location: $location");
    }
    printf(
        "<html><h1>Moved</h1><a href="%s">Moved to %1\$s</a></html>",
        htmlspecialchars($location)
    );
    exit();
}

这不仅会提供更好的重定向响应消息,它还允许您(出于调试目的)禁用该header(...);行(例如通过注释它),以便您的浏览器不再进入重定向循环。

只需更换电话

header("Location: dictionary.php");

site_redirect("dictionary.php");

这样header()您的所有脚本中就只有一个调用,并且在函数内部site_redirect()因此您可以在中心位置影响重定向。

于 2013-04-16T23:28:13.670 回答