繁体   English   中英

即使AngularJS和PHP的凭据不正确,登录仍然会指示

[英]Login still directs even if incorrect credential with AngularJS and PHP

PHP代码需要从表中获取数据,将其解码为JSON,然后将其发送到AngularJS。

如果登录凭据正确,Angular JS会重定向。

但是,即使凭据不正确,仍然会重定向用户(true语句始终通过)。

PHP代码:

 <?php
    $data = json_decode(file_get_contents("php://input"));

    $username = $data->username;
    $password = $data->password;

     /*
   * Collect all Details from Angular HTTP Request.
   */ require_once("connection.php");
    //must read from table
    $connection = connectToMySQL();
    //complete from here

    $query = "SELECT count(*) FROM tbl_admin WHERE username = '$username' AND password = '$password'";
    $result = mysqli_query($connection ,$query);
    $row = mysqli_fetch_row($result);
    $count = $row[0];

    if($count == 1)
    {
        echo true;
    }
    else 
    {
        echo false;
    }

?>

AngularJS控制器:

app.controller('loginCtrl', function ($scope, $http, $location) {
   /*
    * This method will be called on click event of button.
    * Here we will read the email and password value and call our PHP file.
    */
    $scope.checkCredentials = function (credentials) {
        $http.post('model/getAdmin.php',credentials).success(function(data){
            console.log("true");
            $location.path("/memberList");
      })
      .error(function(err){
          $log.error(err);
          console.log("false");
      });
    }
});

HTML表单代码

<form class="form-group" id="customForms" ng-controller="loginCtrl">
        <label> Username </label> 
        <input id="customFormsInput" class="form-control" ng-model="credentials.username" type="text" placeholder="Username goes here" required/>
        <br> 
        <label> Password </label>
        <input id="customFormsInput" class="form-control" ng-model="credentials.password" type="password" placeholder="Password goes here" required/>
        <br> <br>
        <button class="btn btn-primary" type="submit" ng-click="checkCredentials(credentials)"> Submit </button>
        <br>
            {{responseMessage}}
            <!-- Shows message depending on login type -->
    </form>

您必须向success回调添加if-else条件,因为即使您从PHP代码发送false ,您总是发送200响应:

$scope.checkCredentials = function (credentials) {
  $http.post('model/getAdmin.php',credentials).success(function(data){
        console.log("true", data);
        if (data == true) {    // Or in whatever form you are receiving true/false
            $location.path("/memberList");
        } else {
            $log.error(err);
            console.log("false");
        }
  })
}

如果你想让你的旧代码工作,即在Angular中successerror回调,那么你需要从你的PHP代码中发送一个非200响应代码和false ,如:

if($count == 1)
{
    echo true;
}
else 
{
    http_response_code(406);       // not acceptable response code
    echo false;
}

(推荐第二种解决方案)

我从未使用过PHP,所以请确保http_response_code(406); 写得正确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM