即使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>

您必须将if-else条件添加到success回调中,因为即使您从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");
        }
  })
}

如果你想让你的旧代码工作,即与success&在Angular中的error回调,然后你需要从你的PHP代码中发送一个非200响应代码和false,比如:

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

(推荐第二种解决方案)

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