简体   繁体   中英

Decode Json data into PHP Variables

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)

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 .

在AngularJS中使用$ http.post,然后传递带有帖子的JSON数据,然后在PHP中将$ _POST变量与json_decode一起使用,然后在PHP中将有一个关联数组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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