使用 PHP 接收 JSON POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18866571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:21:02  来源:igfitidea点击:

Receive JSON POST with PHP

phpjsonpost

提问by Pablo Ramirez

I'm trying to receive a JSON POST on a payment interface website, but I can't decode it.

我正在尝试在支付接口网站上接收 JSON POST,但我无法对其进行解码。

When I print :

当我打印时:

echo $_POST;

I get:

我得到:

Array

I get nothing when I try this:

当我尝试这个时,我什么也没得到:

if ( $_POST ) {
    foreach ( $_POST as $key => $value ) {
        echo "llave: ".$key."- Valor:".$value."<br />";
    }
}

I get nothing when I try this:

当我尝试这个时,我什么也没得到:

$string = $_POST['operation'];
$var = json_decode($string);
echo $var;

I get NULL when I try this:

当我尝试这个时,我得到 NULL:

$data = json_decode( file_get_contents('php://input') );
var_dump( $data->operation );

When I do:

当我做:

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

I get:

我得到:

NULL

The JSON format is (according to payment site documentation):

JSON 格式为(根据支付站点文档):

{
   "operacion": {
       "tok": "[generated token]",
       "shop_id": "12313",
       "respuesta": "S",
       "respuesta_details": "respuesta S",
       "extended_respuesta_description": "respuesta extendida",
       "moneda": "PYG",
       "monto": "10100.00",
       "authorization_number": "123456",
       "ticket_number": "123456789123456",
       "response_code": "00",
       "response_description": "Transacción aprobada.",
       "security_information": {
           "customer_ip": "123.123.123.123",
           "card_source": "I",
           "card_country": "Croacia",
           "version": "0.3",
           "risk_index": "0"
       }
    }
}

The payment site log says everything is OK. What's the problem?

支付站点日志说一切正常。有什么问题?

回答by Dom

Try;

尝试;

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];

From your json and your code, it looks like you have spelled the word operationcorrectly on your end, but it isn't in the json.

从您的 json 和您的代码来看,您似乎已经正确拼写了operation一词,但它不在 json 中。

EDIT

编辑

Maybe also worth trying to echo the json string from php://input.

也许也值得尝试从 php://input 回显 json 字符串。

echo file_get_contents('php://input');

回答by Steve Chan

If you already have your parameters set like $_POST['eg'] for example and you don't wish to change it, simply do it like this:

例如,如果您已经将参数设置为 $_POST['eg'] 并且您不想更改它,只需这样做:

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

This will save you the hassle of changing all $_POST to something else and allow you to still make normal post requests if you wish to take this line out.

这将为您省去将所有 $_POST 更改为其他内容的麻烦,并且如果您希望删除此行,您仍然可以进行正常的发布请求。

回答by XtraSimplicity

It is worth pointing out that if you use json_decode(file_get_contents("php://input"))(as others have mentioned), this will fail if the string is notvalid JSON.

值得指出的是,如果您使用json_decode(file_get_contents("php://input"))(正如其他人所提到的),如果字符串不是有效的 JSON ,这将失败。

This can be simply resolved by first checking if the JSON is valid. i.e.

这可以通过首先检查 JSON 是否有效来简单解决。IE

function isValidJSON($str) {
   json_decode($str);
   return json_last_error() == JSON_ERROR_NONE;
}

$json_params = file_get_contents("php://input");

if (strlen($json_params) > 0 && isValidJSON($json_params))
  $decoded_params = json_decode($json_params);

Edit:Note that removing strlen($json_params)above may result in subtle errors, as json_last_error()does notchange when nullor a blank string is passed, as shown here: http://ideone.com/va3u8U

编辑:请注意,除strlen($json_params)上述可能导致细微的错误,因为json_last_error()不是在改变null或空字符串传递,如下所示: http://ideone.com/va3u8U

回答by Urisavka

Use $HTTP_RAW_POST_DATAinstead of $_POST.

使用$HTTP_RAW_POST_DATA代替$_POST

It will give you POST data as is.

它将按原样为您提供 POST 数据。

You will be able to decode it using json_decode()later.

json_decode()稍后您将能够对其进行解码。

回答by giuseppe

Read the doc:

阅读文档:

In general, php://input should be used instead of $HTTP_RAW_POST_DATA.

一般来说,应该使用 php://input 而不是 $HTTP_RAW_POST_DATA。

as in the php Manual

就像在php 手册中一样

回答by hyperCoder

$data = file_get_contents('php://input');
echo $data;

This worked for me.

这对我有用。

回答by Luca Reghellin

I'd like to post an answer that also uses curl to get the contents, and mpdfto save the results to a pdf, so you get all the steps of a tipical use case. It's only raw code (so to be adapted to your needs), but it works.

我想发布一个答案,该答案也使用 curl 获取内容,并使用mpdf将结果保存为 pdf,以便您获得典型用例的所有步骤。它只是原始代码(因此可以适应您的需求),但它可以工作。

// import mpdf somewhere
require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';

// get mpdf instance
$mpdf = new \Mpdf\Mpdf();

// src php file
$mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
// where we want to save the pdf
$mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';

// encode $_POST data to json
$json = json_encode($_POST);

// init curl > pass the url of the php file we want to pass 
// data to and then print out to pdf
$ch = curl_init($mysrcfile);

// tell not to echo the results
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );

// set the proper headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);

// pass the json data to $mysrcfile
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

// exec curl and save results
$html = curl_exec($ch);

curl_close($ch);

// parse html and then save to a pdf file
$mpdf->WriteHTML($html);
$this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);

In $mysrcfile I'll read json data like this (as stated on previous answers):

在 $mysrcfile 中,我将读取这样的 json 数据(如之前的答案所述):

$data = json_decode(file_get_contents('php://input'));
// (then process it and build the page source)