Login is still being directed even if the credentials are incorrect using AngularJS and PHP

The PHP code should extract the data from the table, decode it as JSON, and then send it to AngularJS.

Angular JS redirects if login credentials are correct.

However, even if the credentials are incorrect, the user is still redirected (the true statement is always executed).

PHP code:

<?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 controller:

 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 code

 <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> 
+5
source share
1 answer

You need to add an if-else to your success return message, since you always send 200 responses, even if you send false from your PHP code:

 $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"); } }) } 

If you want your old code to work, i.e. with success and error callbacks in Angular, then you need to send a non-200 response code along with false from your PHP code, for example:

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

(recommended second solution)

I have never worked in PHP, so make sure http_response_code(406); spelled correctly.

+2
source

Source: https://habr.com/ru/post/1238629/


All Articles