1

Im sending my data to PHP file like this using angularJS ajax

{ username: "someusername", password: "somepassword" }

previously i used something like this to send data

var vars = "username="+fn+"&password="+ln;

but since angular sending data like JSON. i want to decode into PHP variables.

here my PHP code

if(isset($_POST['username']) && isset($_POST['password'])){
    $username = $_POST['username'];
    $password = $_POST['password'];
}

$sql = "SELECT * FROM member WHERE username = '$username' AND password = '$password'";

what i tried to do is something like this

$array = json_decode(file_get_contents('php://input'))
    $username = $array->username;
    $password = $array->password;


$sql = "SELECT * FROM member WHERE username = '$username' AND password = '$password'";

but not sure how to do it. also no idea about what happens in this section 'file_get_contents('php://input')' im sending data from local computer to internet server PHP file (Cross Domain)

chathura
  • 161
  • 1
  • 9

2 Answers2

0

To transform a PHP array into variables use the extract function, however, this is not a good approach.

Decode the JSON into an array and use PHP's filter functions

On the client side you need something like:

$http.post(http://your.url,
  {"username"  : someUserName, "password": somePassword}
).then(function (data, status, headers, config) {
  // do things.
});

On the server side you should have:

$input = json_decode( file_get_contents('php://input'), true );

$username = filter_var($array['username'], FILTER_SANITIZE_STRING));
$password = filter_var($array['password'], FILTER_UNSAFE_RAW));


// this should work but is bad practice. Don't do it.
// extract($input);
// $username and $password are now available to you

Also, you need to improve you code to protect against SQL injection.

You can read about it here: how-can-i-prevent-sql-injection-in-php .

Community
  • 1
  • 1
VRPF
  • 3,118
  • 1
  • 14
  • 15
  • it worked with your previous edit. `$username = $array['username']; $password = $array['password'];` – chathura Feb 14 '15 at 21:32
  • using this method is a better approach and also much more clear. I further improved my answer to include filters. – VRPF Feb 14 '15 at 21:49
-1

Use $http.post in AngularJS, then pass in the JSON-data with a post, then just use the $_POST variable in PHP with json_decode, then you will have an associative array in PHP.

TRGWII
  • 648
  • 5
  • 14