Receive JSON POST with PHP

PhpJsonPost

Php Problem Overview


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

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:

$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):

{
   "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?

Php Solutions


Solution 1 - Php

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.

EDIT

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

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

Solution 2 - Php

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 = 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.

Solution 3 - Php

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.

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

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

Solution 4 - Php

Use $HTTP_RAW_POST_DATA instead of $_POST.

It will give you POST data as is.

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

Solution 5 - Php

Read the doc:

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

as in the php Manual

Solution 6 - Php

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

This worked for me.

Solution 7 - Php

You can use bellow like.. Post JSON like bellow

enter image description here

Get data from php project user bellow like

// 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'];

Solution 8 - Php

Quite late.
It seems, (OP) had already tried all the answers given to him.
Still if you (OP) were not receiving what had been passed to the ".PHP" file, error could be, incorrect URL.
Check whether you are calling the correct ".PHP" file.
(spelling mistake or capital letter in URL)
and most important
Check whether your URL has "s" (secure) after "http".
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.

Solution 9 - Php

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. (provided you are HTTP with tcp/tls and not udp/quic)

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

Solution 10 - Php

The decoding might be failing (and returning null) because of php magic quotes.

If magic quotes is turned on anything read from _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.

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']));

Solution 11 - Php

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. 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):

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPablo RamirezView Question on Stackoverflow
Solution 1 - PhpDomView Answer on Stackoverflow
Solution 2 - PhpSteve CView Answer on Stackoverflow
Solution 3 - PhpXtraSimplicityView Answer on Stackoverflow
Solution 4 - PhpUrisavkaView Answer on Stackoverflow
Solution 5 - PhpgdmView Answer on Stackoverflow
Solution 6 - PhphyperCoderView Answer on Stackoverflow
Solution 7 - PhpEnamul HaqueView Answer on Stackoverflow
Solution 8 - Phpsifr_dot_inView Answer on Stackoverflow
Solution 9 - PhpJonathanCView Answer on Stackoverflow
Solution 10 - PhpDaan BakkerView Answer on Stackoverflow
Solution 11 - PhpLuca ReghellinView Answer on Stackoverflow