PHP log in error undefined index

2020-05-09 01:48发布

问题:

I am trying to log in using this code :

session_start();

require "connect.php";

$username = $_POST['username'];
$password = $_POST['password'];

  if($username&&$password)
 {
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrow = mysql_num_rows($query);

if($numrow!=0)
{
    while($row = mysql_fetch_assoc($query))
    {
        $db_username = $row['username'];
        $db_password = $row['password'];
    }

    if($username==$db_username&&$password==$db_password)
    {
        //echo 1;
        header("Location: members.php");
        $_SESSION['username']=$db_username;

    }
    else echo 0;
}
else die("That user doesn't exist");
    }
     else die("Please enter a username and password");

upon successful log in it should take me to members.php :

 session_start();
 if($_SESSION['username'])  <------ this is line 5
   {
echo "20730312";
echo " You are logged in as: ".$_SESSION['username'];
echo "<p><a href='logout.php'>Click here to logout</a>";
    }

but when i request members.php in my application it gives me :

Notice: Undefined index: username in E:\Program Files\xampp\htdocs\adddrop\members.php on line 5

note that i am using android webview to request members.php after successful log in, is this right ? what am i doing wrong ?

回答1:

On a side note: you have an SQL injection there. Might want to read more: http://en.wikipedia.org/wiki/SQL_injection

The problem you are facing is that the username is not always POST'd (when you just load the page first time):

$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;

That should fix it. Basically, I check if the POST index is set, and only if it is I try to access it, otherwise I set it to null.

Also, you might want to do it like this:

$query = mysql_query("SELECT * FROM users WHERE username='" . mysql_real_escape_string($username) . "'");

That prevents the SQL injection vulnerability.

And also add exit;:

header("Location: members.php");
$_SESSION['username']=$db_username;
exit; // Add this.


回答2:

Same as always. You're not POSTing to the URL. Verify the URL you're attempting to POST to.



回答3:

perhaps this:

header("Location: members.php");
$_SESSION['username']=$db_username;

should be changed to (reverse):

$_SESSION['username']=$db_username;
header("Location: members.php");


回答4:

As it says, you don't have the specified data from POST. Make sure your form action is right and you're filling out the username.

Also, you might want to consider hashing your passwords. From what I can see here you compare plain text passwords (or you're already getting hashed passwords to your script, which would be ok).