PHP会话问题

时间:2013-04-16 23:13:42

标签: php session authentication

我遇到了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方法的表单发送$username$password,以防你还没注意到。

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

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

感谢。

2 个答案:

答案 0 :(得分: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的情况,就会导致无限重定向。你需要清理它。

答案 1 :(得分: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()函数,因此您可以在中心位置影响重定向。 / p>