Json_decode returns string(0) "" - php

I am trying to pass data from ios to server.
Php code :
<?php
$inputJSON = file_get_contents('php://input');
$data = json_decode($inputJSON, TRUE);
var_dump($data);
?>
This gives me string(0) "". I don't know whats the meaning of this.
echo $inputJSON; gives nothing
var_dump($inputJSON); returns string(0) ""
When i print the json-string it gives me a valid string
Please find the full codes of this problem in another question of mine
Cannot able to access json array in php , it returns null and Warning: Invalid argument supplied for foreach()

I have created an example for you that what i am talking:-
1.My both file (php code file and json string file) in the same working directory.Check:- http://prntscr.com/apkbp9
2.json string file content should be:-
[
{
"email" : "",
"Name" : "Ddd",
"contact2" : "",
"ontact1" : ""
},
{
"email" : "",
"Name" : "Ddd",
"contact2" : "",
"contact1" : ""
},
{
"email" : "",
"Name" : "Dddddr",
"contact2" : "",
"contact1" : ""
}
]
Check here:- http://prntscr.com/apkbx0
3.php code file content:-
<?php
$inputJSON = file_get_contents('input.txt');
echo $inputJSON;
$data = json_decode($inputJSON, TRUE);
echo "<pre/>";print_r($data);
?>
Check here:- http://prntscr.com/apkc6x
Output on my browser:- http://prntscr.com/apkcoi
You can use CURL like below:-
<?php
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$inputJSON = url_get_contents('php://input');
echo $inputJSON;
$data = json_decode($inputJSON, TRUE);
echo "<pre/>";print_r($data);
?>
For more reference about CURL :- http://php.net/manual/en/book.curl.php
Note:- if both will not work, then first you need to save your json data in a file with extension .txt and then you can use both code given above, just by putting the full path of that text file.

fisrt you should check is your url is correct or not. If every thing is right but still its not showing the response use curl functionality such as alter native of file_get_content

With God Grace solved my problem-
pass true to convert objects to associative arrays, so accessing numeric/associative array like this.
$var = $data[0]['key'];
Then we use a combination of numeric and associative array syntax to access the desired element in multidimensional array.
But if i trying to var_dump($data); is retun null.
Reference tutorial: http://www.dyn-web.com/tutorials/php-js/json/decode.php

Related

PHP POST Request Receiving Null Variables [duplicate]

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?
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');
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.
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
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.
Read the doc:
In general, php://input should be used instead of $HTTP_RAW_POST_DATA.
as in the php Manual
$data = file_get_contents('php://input');
echo $data;
This worked for me.
You can use bellow like..
Post JSON like bellow
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'];
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.
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
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']));
I got "null" when I tried to retrieve a posted data in PHP
{
"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
}
You should avoid commenting JSON code even if it shows no errors
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)

Trouble With API Curl Response(php)

I am having trouble with the response from Companies House API. I am making the following curl request from a php page:
$request_url_1 ='https://api.companieshouse.gov.uk/company/' ;
$company_number = 11495745;
$request_url_2 = '/officers';
$request_url = $request_url_1 . $company_number . $request_url_2;
$ch = curl_init($request_url);
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '. base64_encode("$chkey:")
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$content = curl_exec($ch);
curl_close( $ch );
$contents = json_decode($content,true);
The following is the response that is 'pasted' on the php page after sending the curl request, and I cannot seem to get at the contents/value of the $contents variable that should contain the curl response.
{
"active_count":1,
"items_per_page":35,
"kind":"officer-list",
"etag":"6cc48213158205c9fa85492a4c2ef0a98b56b2f1",
"resigned_count":2,
"items":[
{
"date_of_birth":{
"year":1963,
"month":2
},
"appointed_on":"2019-08-01",
"nationality":"British",
"address":{
"address_line_1":"Moorside Crescent",
"country":"United Kingdom",
"address_line_2":"Sinfin",
"postal_code":"DE24 9PH",
"locality":"Derby",
"premises":"75"
},
"occupation":"Company Director",
"links":{
"officer":{
"appointments":"/officers/IryiaaBZodlGNaOP0Rf3Pb2GnO8/appointments"
}
},
"name":"MILLER, Eira",
"country_of_residence":"England",
"officer_role":"director"
},
{
"date_of_birth":{
"month":3,
"year":1987
},
"nationality":"English",
"occupation":"Company Director",
"address":{
"locality":"Derby",
"address_line_1":"Moorside Crescent",
"premises":"75",
"country":"United Kingdom",
"postal_code":"DE24 9PH",
"address_line_2":"Sinfin"
},
"appointed_on":"2018-12-10",
"resigned_on":"2019-07-31",
"name":"KING, Kimberley Rachel",
"links":{
"officer":{
"appointments":"/officers/av7G3-iF_9-FXhRH2xm-IxejeGQ/appointments"
}
},
"country_of_residence":"United Kingdom",
"officer_role":"director"
},
{
"address":{
"postal_code":"DE24 9PH",
"locality":"Derby",
"country":"United Kingdom",
"premises":"75",
"address_line_2":"Sinfin",
"address_line_1":"Moorside Crescent"
},
"occupation":"Managing Director",
"nationality":"British",
"appointed_on":"2018-08-01",
"resigned_on":"2018-12-10",
"officer_role":"director",
"country_of_residence":"United Kingdom",
"links":{
"officer":{
"appointments":"/officers/X9nlVD6qIIENMjaH946__4CB3QE/appointments"
}
},
"name":"MARTIN, Katey",
"date_of_birth":{
"month":6,
"year":1968
}
}
],
"links":{
"self":"/company/11495745/officers"
},
"inactive_count":0,
"start_index":0,
"total_results":3
}
I have tried returning result as non-associative array and access it through normal array but no joy there either.
FluffyKitten kindly supplied the following code to perform the extraction of the name field:
$item = $contents["items"];
foreach($item as $items){
echo $items["name"];
}
However, this couldn't access the required data. A print_r of $contents results in '1' and a var_dump (1)
There are a couple of problem with your code:
You are mixing up code for accessing arrays and objects
You are looping when there is no need for loops
You are using json_decode($content,true), and by passing in that true parameter, you are converting the result into associative arrays, but then you try to access items as the property of an object.
Because you have converted the contents to an associative array, you can easily access the information you want using the correct keys, e.g.:
$item = $contents["items"];
foreach($item as $items){
echo "<p>".$items["name"];
}
Reference PHP json_decode Documentation
UPDATE:
Your question has changed totally - it was about how to loop through the variable with the results, but now it seems that the problem is saving the results as a variable in the first place.
You need to set the CURLOPT_RETURNTRANSFER option to true so that the result is not output directly (I assume this is what you mean by the result being "pasted" into the PHP page).
Add this to your CURL code, and if the rest of your code is correct, the result should be saved in the $content variable so you can use it to loop through using the code above:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

Simple curl with JSON data to PHP script yields empty $_POST [duplicate]

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?
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');
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.
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
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.
Read the doc:
In general, php://input should be used instead of $HTTP_RAW_POST_DATA.
as in the php Manual
$data = file_get_contents('php://input');
echo $data;
This worked for me.
You can use bellow like..
Post JSON like bellow
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'];
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.
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
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']));
I got "null" when I tried to retrieve a posted data in PHP
{
"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
}
You should avoid commenting JSON code even if it shows no errors
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)

Problems parsing JSON with PHP (CURL)

I am trying to access the value for one of the currencies (e.g. GBP) within the "rates" object of the following JSON file:
JSON file:
{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}
This was my approach:
PHP (CURL):
$url = ...
// initialize CURL:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// get the (still encoded) JSON data:
$json = curl_exec($ch);
curl_close($ch);
// store decoded JSON Response in array
$exchangeRates = (array) json_decode($json);
// access parsed json
echo $exchangeRates['rates']['GBP'];
but it did not work.
Now, when I try to access the "timestamp" value of the JSON file like this:
echo $exchangeRates['timestamp'];
it works fine.
Any ideas?
Try removing (array) in front of json_decode and adding true in second parameter
Here is the solution.
$exchangeRates = (array) json_decode($json,TRUE);
https://ideone.com/LFbvUF
What all you have to do is use the second parameter of json_decode function.
This is the complete code snippet.
<?php
$json='{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}';
$exchangeRates = (array) json_decode($json,TRUE);
echo $exchangeRates["rates"]["GBP"];
?>

JSON to PHP Output

I usually manage to figure stuff out by myself, but on this occasion I've had to register an account and ask for help before I jump out the window.
I'm trying to output some basic JSON data to php, all I need to do is echo it out, the rest I'll figure out.
The API gives this guide:
{
"success" : true,
"message" : "",
"result" : {
"Bid" : 2.05670368,
"Ask" : 3.35579531,
"Last" : 3.35579531
}
}
An example of the URL I'll be using: https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC
All I want to output is the 'Last' data, I don't care about the rest, keeping the decimal in the right place is also important.
I've tried all sorts, I can't get it to output it properly :(. I've ran a var_dump which spits out:
array(3) { ["success"]=> bool(true) ["message"]=> string(0) "" ["result"]=> array(3) { ["Bid"]=> float(0.00011505) ["Ask"]=> float(0.000116) ["Last"]=> float(0.00011505) } }
If someone could just tell me the few lines of code to put the 'Last' number into a variable called $lastBid I will love you long time!
Thanks guys!
use json_decode - php method to decode json
http://php.net/manual/en/function.json-decode.php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
Here you have an example,
$contents = file_get_contents("https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC");
$json = json_decode($contents);
$lastBid = $json->result->Last;
$lastBid would then be set to 0.01189802
You need to json_decode() the result.
that kind of data is called json. php permits you to convert that json (which is a string) to a php array.
to get it, you need to convert it and then access to the value you'd like using array rules.
// save in a variable the data you're going to process
$json = '{
"success" : true,
"message" : "",
"result" : {
"Bid" : 2.05670368,
"Ask" : 3.35579531,
"Last" : 3.35579531
}
}';
// json_decode is a function that allows you to obtain an array
// (the second parameter set to true indicates that the array'll be an associative one)
$data = json_decode($json, TRUE);
/*
every php array has an internal pointer which points to a position in the array.
the end pointer, if not moved, points to the last position. to access to the value
you want, first get the last value (an array called "result"),
then access to the last value of that array (called "last").
the property you'll get is the float value you requested!
*/
var_dump(
end(
end($data)
)
);
and here, there is the output:
float(3.35579531)
Access it by:
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = file_get_contents($url);
$data = json_decode($data);
$last = $data->result->Last;
If you like using arrays instead of object orrientation style, json_decode has an extra boolean param, that converts it too an array if you feel more comfortable using that.
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = file_get_contents($url);
$data = json_decode($data,true);
$last = $data['result']['Last'];
Side note; For accessing API's I would rather advice you to use curl instead of file_get_contents. It gives you better control, for instance with timeouts. But you have many more options. You can use this function;
function curl($URL,&$errmsg){
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$contents = curl_exec($c);
if (curl_errno($c)){
$errmsg = 'Failed loading content.';
curl_close($c);
return;
}
else{
curl_close($c);
return($contents);
}
}
And your code then would be:
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = curl($url, $errmsg);
$data = json_decode($data,true);
$last = $data['result']['Last'];

Categories