开发者

How to check which one of the username or password is incorrect?

I want to check which one of the username or password is incorrect in a single mysql query.

Scenario:

When a user types a username and password and clicks submit, I want to show an error message which one is inco开发者_高级运维rrect. I need a simple and optimized query for this.


As a general rule of thumb I would say it's better return a message back to the user saying that "The username or password is incorrect" as it wouldn't indicate to an attacker if the username or password was wrong.


That's a nice way for an attacker to find valid usernames.

To answer your question, I think you'd have to do

SELECT username, password WHERE username=? OR password=?

and then go through the results with the given username and password, to find the right one.


$query = <<<EOL
SELECT IF(password = '$password', 1, 0)
FROM users
WHERE username='$username'
EOL;

$result = mysql_query($query)
if (mysql_numrows($result) == 0) then
  echo 'Bad username';
} else {
  $row = mysql_fetch_array($result);
  if ($row[0] == 0) then
     echo 'Bad password';
  }
}

Of course, this assumes $username and $password have been properly escaped, and that $password has been massaged into whatever hash/encryption method you're using to store it in the DB.


Please use HTMl form with POST method the use following code::

 <?php
    $con = mysql_connect("localhost","username","password");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());

      }
    mysql_select_db("My_TABLE_NAME", $con); 
    $Username = $_POST['Username']; // get username
    $Password = $_POST['Password'] ; // get pwd

    $sql="SELECT Username FROM My_TABLE_NAME WHERE Username=’".$Username.”’ and Password=’”.$Password.”’”;
    $r = mysql_query($sql);
    if(!$r) {
       $err=mysql_error();
       print $err;
       exit();
    }
    if(mysql_affected_rows()==0){
       print "no such login in the system. please try again.";
       exit();
    }
    else{
       print "successfully logged into system.";
       //proceed to perform website’s functionality – e.g. present information to the user
    }
    ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜