Brad Hazelnut
Brad Hazelnut

Reputation: 1621

PHP submit to self form

I am trying to create a login page and have it to submit to itself and then redirect based on if user is authenticated. But for some reason everytime i submit, with wrong username or password, i would like it to show the log in screen again but it just shows blank. But if i login correctly then it works.

<?php 
if (!empty($_POST)){ 

require_once 'includes/db.php';

    if($user->login($_POST["username"], $_POST["password"]))
        echo "user is logged in";   
}else{
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>

<body>
<form action="" method="post">
<table align="center">
    <tr>
        <td>User name:</td>
        <td>Password: </td>
    </tr>
    <tr>
        <td><input type="text" name="username" /></td>
        <td><input type="password" name="password" /></td>
    </tr>
    <tr>
        <td><input type="submit" value="Login" /></td>
    </tr>
</table>
</form>
</body>
</html>
<?php
}
?>

Upvotes: 0

Views: 86

Answers (2)

Noah Wetjen
Noah Wetjen

Reputation: 1785

That's because your !empty($_POST) clause triggers because the $_POST variable isn't empty, as you just send some login credentials (they may be wrong but that doesn't matter).

The else clause just triggers when nothing is sent, so basically whenever you submit anything with the form, if the login credentials are right user is logged in will appear and if they are wrong, nothing will be put out whatsoever.

The easiest way to solve this would be to remove the else clause entirely and add exit() into the if clause checking the credentials like so:

<?php 
    if (!empty($_POST)) { 
        require_once 'includes/db.php';

        if ($user->login($_POST["username"], $_POST["password"])) {
            echo "user is logged in";

            /* Add exit() if you don't want the form to show
               up when login attempt was successful. */
        }
    }
?>

<!-- HTML CODE -->

Upvotes: 1

Kirs Sudh
Kirs Sudh

Reputation: 298

check the syntax correctly...

if($user->login($_POST["username"], $_POST["password"]))
{
        //if login success, then redirect to index.php
        header('Location:index.php');
}else{
        //if username and pass do not match or login fails, redirect to login.php

?>

Upvotes: 0

Related Questions