PHP无法正确检测会话变量值

时间:2013-12-10 19:35:56

标签: php session login

我正在尝试进行PHP登录,并在登录时显示登出按钮,如果没有登录则显示登录表单。这是显示代码的表单和按钮:

    <?php if ($_SESSION["login"] == "1") { ?>
        <form class="form-signin" method="post">
            <h2 class="form-signin-heading">You are signed in!</h2>
            <input type="hidden" name="op" value="logout">
            <button class="btn btn-lg btn-primary btn-block" type="submit">Log out</button>
        </form>
    <?php } else { ?>
        <form class="form-signin" method="post">
            <h2 class="form-signin-heading">Sign in</h2>
            <input type="text" class="form-control" placeholder="Username" name="user" required="" autofocus="" style="margin:2px 0">
            <input type="password" class="form-control" placeholder="Password" name="pass" required="" style="margin:2px 0">
            <input type="hidden" name="op" value="login">
            <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
        </form>
    <?php }; ?>

以下是启动会话并设置变量login的代码:

if (isset($_REQUEST["user"]) && isset($_REQUEST["pass"]) && isset($_REQUEST["op"]) && $_REQUEST["op"] == "login") {
                $user = $_REQUEST["user"];
                $pass = $_REQUEST["pass"];
                $con = mysql_connect("localhost", USER, PASS);
                if (!$con) {
                    die("Could not connect: " . mysql_error());
                }
                mysql_select_db("reddit", $con);
                $sql = mysql_query("SELECT username from t120937_users WHERE t120937_users.username = '" . $user . "' AND t120937_users.password = '" . $pass . "';");
                if (mysql_num_rows($sql) > 0) {
                    session_start();
                    $_SESSION["login"] = "1";
                    header("Location: /~rauno.sams/");
                } else {
                    echo "Incorrect login information :(";
                }
                mysql_close($con);
            }
            if(isset($_REQUEST["op"]) && $_REQUEST["op"] == "logout") {
                $_SESSION["login"] = "";
                session_destroy();
                header("Location: /~rauno.sams/");
            }

但是,每次都会显示登录表单,我不知道原因。

1 个答案:

答案 0 :(得分:0)

你的选择陈述有额外的;在里面。所以你的mysql_num_rows是0,它没有登录你。