Question

I am trying to make a PHP login and make it show a logout button if logged in and show the login form if not logged in. Here is the form and button showing code:

    <?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 }; ?>

Here is the code that starts the session and sets the variable 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/");
            }

However, the login form is displayed every time and I don't know why.

Était-ce utile?

La solution

Your select statement has an extra ; in it. So your mysql_num_rows is 0, which is not logging you in.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top