简体   繁体   English

使用 PHP 接收 JSON POST

[英]Receive JSON POST with PHP

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?有什么问题?

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 operation correctly 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');

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 更改为其他内容的麻烦,并且如果您希望删除此行,您仍然可以发出正常的 post 请求。

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 not valid JSON.值得指出的是,如果您使用json_decode(file_get_contents("php://input")) (正如其他人所提到的),如果字符串不是有效的 JSON,这将失败。

This can be simply resolved by first checking if the JSON is valid.这可以通过首先检查 JSON 是否有效来简单地解决。 ie 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 not change when null or a blank string is passed, as shown here: http://ideone.com/va3u8U编辑:请注意,删除上面的strlen($json_params)可能会导致细微的错误,因为json_last_error()在传递null或空白字符串时不会改变,如下所示:http: //ideone.com/va3u8U

Use $HTTP_RAW_POST_DATA instead 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()对其进行解码。

Read the doc:阅读文档:

In general, php://input should be used instead of $HTTP_RAW_POST_DATA.通常,应使用 php://input 而不是 $HTTP_RAW_POST_DATA。

as in thephp Manualphp 手册中所述

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

This worked for me.这对我有用。

You can use bellow like.. Post JSON like bellow你可以像下面这样使用.. 像下面这样发布 JSON

在此处输入图像描述

Get data from php project user bellow like从下面的php项目用户获取数据

// takes raw data from the request 
$json = file_get_contents('php://input');
// Converts it into a PHP object 
$data = json_decode($json, true);

 echo $data['requestCode'];
 echo $data['mobileNo'];
 echo $data['password'];

Quite late.很晚了。
It seems, (OP) had already tried all the answers given to him.看来,(OP)已经尝试了所有给他的答案。
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.不过,如果您(OP)没有收到传递给“.PHP”文件的内容,则错误可能是 URL 不正确。
Check whether you are calling the correct ".PHP" file.检查您是否调用了正确的“.PHP”文件。
(spelling mistake or capital letter in URL) (网址中的拼写错误或大写字母)
and most important重要的是
Check whether your URL has "s" (secure) after "http".检查您的 URL 在“http”之后是否有“s”(安全)。
Example:例子:

"http://yourdomain.com/read_result.php"

should be应该

"https://yourdomain.com/read_result.php"

or either way.或任何一种方式。
add or remove the "s" to match your URL.添加或删除“s”以匹配您的 URL。

If all of the above answers still leads you to NULL input for POST, note that POST/JSON in a localhost setting, it could be because you are not using SSL.如果以上所有答案仍然导致您为 POST 输入 NULL,请注意 localhost 设置中的 POST/JSON,这可能是因为您没有使用 SSL。 (provided you are HTTP with tcp/tls and not udp/quic) (前提是您是带有 tcp/tls 而不是 udp/quic 的 HTTP)

PHP://input will be null on non-https and if you have a redirect in the flow, trying configuring https on your local as standard practice to avoid various issues with security/xss etc PHP://input 将在非 https 上为空,如果您在流程中有重定向,请尝试在本地配置 https 作为标准做法以避免各种安全/xss 等问题

The decoding might be failing (and returning null) because of php magic quotes.由于 php 魔术引号,解码可能会失败(并返回 null)。

If magic quotes is turned on anything read from _POST/_REQUEST/etc.如果魔术引号打开了从 _POST/_REQUEST/etc 读取的任何内容。 will have special characters such as "\ that are also part of JSON escaped. Trying to json_decode( this escaped string will fail. It is a deprecated feature still turned on with some hosters.将有特殊字符,例如"\ ,它们也是 JSON 的一部分。尝试json_decode(这个转义字符串将失败。这是一个已弃用的功能,但某些主机仍然打开。

Workaround that checks if magic quotes are turned on and if so removes them:检查魔术引号是否打开的解决方法,如果是,则将其删除:

function strip_magic_slashes($str) {
    return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}

$operation = json_decode(strip_magic_slashes($_POST['operation']));

I got "null" when i tried to retrieve a posted data in php当我尝试在 php 中检索发布的数据时,我得到了“null”

{
    "product_id": "48",
    "customer_id": "2",  
    "location": "shelf",  // shelf, store <-- comments create php problems
    "damage_types":{"Pests":1, "Poke":0, "Tear":0}
     // "picture":"jhgkuignk"  <-- comments create php problems
}

Avoid commenting json code even if it show no erros避免注释 json 代码,即使它没有显示错误

I'd like to post an answer that also uses curl to get the contents, and mpdf to save the results to a pdf, so you get all the steps of a tipical use case.我想发布一个答案,该答案也使用 curl 获取内容,并使用 mpdf将结果保存到 pdf,因此您可以获得典型用例的所有步骤。 It's only raw code (so to be adapted to your needs), but it works.它只是原始代码(以便适应您的需求),但它可以工作。

// 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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