在PHP ajax中单独验证用户名和密码

时间:2014-08-22 12:53:24

标签: php jquery ajax validation

我有一张登录表格。如下:

<form id="myform"  method="POST" class="form_statusinput">
   <div class="input-group">
     <span class="input-group-addon"><i class="fa fa-user"></i></span>
     <input type="email" class="form-control" id="email" name="email" 
      placeholder="Enter email" data-original-title="" title="" 
      onblur="checkEmail()">
      </div>
      <br>
      <div class="input-group">
      <span class="input-group-addon"><i class="fa fa-lock"></i></span>
      <input type="password" class="form-control" id="password" name="password" 
       placeholder="Password" data-original-title="" title="" 
       onblur="checkPass()">
     </div>
</form>       

我在提交表格时通过Ajax验证用户名和密码

$(document).ready(function(){ 
  $("form#myform").submit(function(event) {
  event.preventDefault();
  validate();
  });
});

Validate函数中,对空字符或无效字符进行了正确的验证,但我想向用户返回错误,即密码错误或用户名错误。

Ajax调用如下:

$.ajax({
    url: "includes/fo_submit",
    type: "POST",
    data: dataString,
    success: function (msg) {
        if (msg == 1) {
            $("#loading").hide();
            window.location.reload();
        } else {
            $("#loading").hide();
            $("#messagesuccerr").html("Wrong Credentails")
            .fadeIn().delay(4000).fadeOut();
            return false;
        }
    }
}); 

fo_submit拥有PHP Databse连接和代码

$query = "select * from `register_userfm` where `userchkname_yt` = ? 
and passchk_ty = ?; ";
$result = DB::instance()->prepare($query)->execute(array($_POST['email'],
$_POST['password']))->fetchAll();
if(count($resultfm1)>0){
    echo 1;
}
else{
    echo 0;
}

这种方式只返回错误是“无效的凭据”。请让我知道如何单独验证用户名和密码。

1 个答案:

答案 0 :(得分:1)

您可以通过运行2个不同的查询来使用从PHP脚本返回它们的状态代码。如下所示:

$query = "select * from `register_userfm` where `userchkname_yt` = ? and passchk_ty = ?; ";
$result = DB::instance()->prepare($query)->execute(array($_POST['email'], $_POST['password']))->fetchAll();
if(count($result)>0){
    echo "1"; //auth success
}
else{
    $query = "select * from `register_userfm` where `userchkname_yt` = ?;";
    $result = DB::instance()->prepare($query)->execute(array($_POST['email']))->fetchAll();
    if(count($result)>0){
        echo -1; //password wrong
    }
    else{
        echo 0; //username wrong
    }
}

然后,您可以检查ajax回调中的返回值并采取相应的行动。

建议:为可能的攻击者提供此信息(他出错了)可以大大降低暴力/字典攻击所需的时间