簡體   English   中英

將Json數據解碼為PHP變量

[英]Decode Json data into PHP Variables

我使用angularJS ajax將數據發送到PHP文件中

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

以前我用這樣的東西發送數據

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

但是由於像JSON這樣的角度發送數據。 我想解碼成PHP變量。

這是我的PHP代碼

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

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

我試圖做的是這樣的

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


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

但不確定如何做。 也不知道在本節中'file_get_contents('php:// input')'發生什么,我將數據從本地計算機發送到Internet服務器PHP文件(跨域)

要將PHP數組轉換為變量,請使用extract函數 ,但這不是一個好方法。

將JSON解碼為數組並使用PHP的過濾器功能

在客戶端,您需要以下內容:

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

在服務器端,您應該具有:

$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

另外,您需要改進代碼以防止SQL注入。

您可以在這里閱讀有關內容: how-can-i-prevent-sql-injection-in-php

在AngularJS中使用$ http.post,然后傳遞帶有帖子的JSON數據,然后在PHP中將$ _POST變量與json_decode一起使用,然后在PHP中將有一個關聯數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM