I am writing some simple PHP to receive a POST from another system with a JSON payload. That request is Content-Type: application/json.
I'm simply attempting to dump the json into a txt file as a starting point, but that isn't happening. Here's the PHP file, any suggestions/corrections would be much appreciated!
<?php
ini_set("display_errors", "On");
session_start();
$raw_json = file_get_contents('php://input');
$cooked_json = json_decode($raw_json);
$myfile = fopen('/home/wgordon/log.txt','a');
$fp = fwrite($myfile, $cooked_json);
fclose($myfile);
?>
From the look of it, the initial value of $raw_json would be a string. When you try to access it as an array, you're only going to get a smaller string back. When you pass that to json_decode, it's probably going to return null.
You need to inspect that first value of $raw_json. If it is coming in as a query string of name/value pairs, you'll need to decode it (using split() or something similar) before you can treat it like an array
Related
Hi everyone i am reading some data from a txt-file with php using
file_get_contents('../../Datafiles/allThreads.txt');
this returns the following string
[{"OP":"ding","threadName":"","content":"","ID":6}]
when i try to vaildate with lint, I have no issues, so the json is valid.
But the problem is that when i call json_decode it keeps returning null:
$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');
Why is this happening? im following all the rules?
You can do it like:
//storing json contents in a variable.
$json_contents = file_get_contents('../../Datafiles/allThreads.txt');
//decode json
$currentThreadasList = json_decode($json_contents, TRUE)
Edit-1:
Have you tried the following:
$currentThreadasList = json_decode(file_get_contents('../../Datafiles/allThreads.txt'), TRUE);
Well, this piece of code
$currentThreadasList = json_decode('../../Datafiles/allThreads.txt');
doesn't work because the first parameter to json_decode needs to be a JSON string, not a path. Just pass the content of the file as parameter like:
$yourJsonDecodedArray = json_decode(file_get_contents('../../Datafiles/allThreads.txt'), TRUE);
I am facing error while getting response from JSON array.
here is PHP code I try this code.
var_dump($_POST);die;
empty
$data = (array) json_decode($HTTP_RAW_POST_DATA, true);
var_dump($data);
empty
$arJson =(array) json_decode( $_POST, true );
var_dump($arJson);
this one also empty here is postman results.
Try this:
$postData = json_decode(file_get_contents("php://input"));
If you simply POST a good old HTML form, the request looks something like this:
POST /page.php HTTP/1.1
key1=value1&key2=value2&key3=value3
But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:
POST /page.php HTTP/1.1
{"key1":"value1","key2":"value2","key3":"value3"}
The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST-wrapper doesn't know how to handle that (yet).
The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it's not multipart/form-data-encoded).
If your whole POST body contains the JSON, you can get it using thid piece of code:
$json = file_get_contents('php://input');
$decoded = json_decode($json);
You can get value like this:
$str = file_get_content("php://input");
$data = json_decode($str,true);
Hope you can help.
I am trying to decode a JSON string in PHP,but somehow the json_decode doesnt like my string, i think it is not valid json. The thing that is very strange to me is, that if i put the json response in a variable manually, it is working. If i write the json response out in the browser, and i write the content of the variable, both are completely the same, like this:
{"id":455463,"Created":"2016-04-30T14:20:38.09","SenderCompanyName":"x","InvoiceNumber":"2555","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}
If i look in the webpage source, the content is also completely the same. I have also tryed to convert to UTF8, but no change.
How do you guys usually debug this, or what did i forget ?
code:
// calling web service and saving json response in variable
$json_response = CallAPI($method, $url, $json_request);
// the response contain some unvalid character in the end, so i am removing it
$json_response = substr($json_response, 0, strpos($json_response, "}"));
// trying to decode it, IT PRINTS OUT NULL
var_dump(json_decode($json_response, true));
// copying the json response from the above and putting it into a variable
$json_response = '{"id":455433,"Created":"2016-04-30T12:55:12.313","SenderCompanyName":"x","InvoiceNumber":"2525","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}';
// trying to decode it, IT PRINTS OUT THE RESULT SUCCESFULLY
var_dump(json_decode($json_response, true));
Try this:
<?php
$json = '{"id":455463,"Created":"2016-04-30T14:20:38.09","SenderCompanyName":"x","InvoiceNumber":"2555","PaymentDueDate":"2016-04-30T00:00:00","ToBePaidAmount":350.0000}';
var_dump(json_decode($json));
?>
I finally found the solution.
I had forget to add this in my CURL OPTIONS:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
After adding this, its working fine
I am working on a php script which receives data sent by android in json format using POST method.
But i am not getting any data, here is my code
$josn = file_get_contents("php://input");
$json_data = json_decode($josn, true);
i just tried to print $json_data by
print_r($json_data);
but its not showing any values
var_dump() is much more reliable than print_r()
Whether the data is corrupt or not, it will tell you 'something' about the thing you are trying to see.
If it is null it will say 'null'.
If it is 'bob' it will say (string 3) 'bob'.
If it is 4 it will say (int) 4
If it is '4' it will say (string 1) '4'
Also, your json_decode() might be breaking if the input is not valid json. A safer way to see if you are getting any data at all is to dump and check your data before you pass it into the json_decode() function:
var_dump( file_get_contents("php://input") );
If you see valid json, then it is safe to pass your $josn variable into the json_decode() function.
Bonus
Seems dumb but it's worth mentioning that you can only use file_get_contents() on the input buffer once and then the contents are gone. If you try to read them again, they will be null. Refer to the variable you stored them in when you first read them.
Separetely
Another fellow mentioned checking your global $_POST[] variable... which brings up a great point. Headers!
For json pickup with file_get_contents('php://input'), php needs your android app to send the header:
header('Content-Type: application/json');
For POST variable pickup with $_POST[], php needs your android app to send the header:
header('Content-Type: application/x-www-form-urlencoded');
OR
header('Content-Type: multipart/form-data');
I'm trying to read data from a decompiled application of Android with a php server. I used wireshark to understand what types of data the application sends, and the result is:
{"initType":"first time","parameters":true,"details":................}
I trying to capture this data and insert them in a file with this php code:
<?php
$json = $_POST["initType"];
$decoded = json_decode($json, TRUE);
if ($decoded === FALSE) {
throw new Exception('Bad JSON format.');
}
$file_handle = fopen('tmp.json', 'w');
fwrite($file_handle, $decoded);
fclose($file_handle);
?>
The file is correctly generated but it's empty. What is the error?
Because $decoded is an array, use a loop to write it to file or write the encoded JSON to file ($json). Try using this:
fwrite('tmp.json', print_r($decoded, TRUE));
or:
file_put_contents('tmp.json', print_r($decoded, TRUE));
Update (per your comments):
If you run a print_r($decoded) and it prints nothing, there is a problem with the decoding process of the JSON object passed in. I would recommend checking this to make sure it is formatted correctly. JSON formatting is a strict business and will halt your end goal if you are missing a double-quote or bracket. Start by echoing out $json ($_POST["initType"]) and compare the format to examples posted online (just Google "json formatting"). I can tell you that one thing that stands out to me is: "parameters":true (from your example above). I have a strong suspicion that the key true should be in double quotes. If you are positive that the JSON variable is correct syntactically, I don't think I would be of any more help. Using json_decode() to produce an array to very straight forward once you get it right.
Don't decode the json at all -this only brings the problem of trying to serialize an array that burmat mentioned in his answer.
Write to the file the json content straight away:
fwrite($file_handle, $json);
Also, though I am not PHP expert it seems you access the body of the post request wrongly. Please refer to the following post.