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');
Related
So I'm quite new to programming, and I have nothing else to describe it but a live script, so please correct me with the official term. Anyway, a while ago, I made this bot in php and ran it locally in my browser using xampp on my mac. I could very easily use echo and print_r to print arrays and whatever to the webpage. The script would only run if I reloaded the page, so this is what i'm talking about as 'not live'. Now I have started trying to make a messenger bot in PHP, and i'm using cloud9. I also see the script in a browser, but here, I can only see products of echo and print if they are simple strings I have entered, for example:
print_r("stack overflow is life");
This will print as expected in my browser. However, this is where me talking about 'live' script runs comes into play. Instead of reloading the page, it runs live. The messenger bot will always be active on the server, and it instantly replies to a message sent to it as wanted. I use this code:
/* receive and send messages */
$input = json_decode(file_get_contents('php://input'), true);
file_put_contents("fb.txt", file_get_contents('php://input'));
echo ("<pre>"); print_r($input);
echo ("</pre>");
Now, in this case, the $input is not printed. I see nothing. Now I don't know if this is to do with live server response, or what, but I need to know how to see this is the browser. And I have tested to see if there actually is a successfully converted JSON to array, because I am able to use the info in $input to reply to my facebook messaged and the bot works. I can also output the JSON to a txt file, and see it there, but there is no <pre> tags so it is hard to read, and I want the nice clean array to see in the browser. All code revolves around this, so it is very important.
So you are writing the raw input to the file and json decoding it separately. So it is quite possible you are not actually getting valid json.
If you do pass invalid json, json_decode returns NULL which is why you see that when you var_dump - so you have to call json_last_error to be sure it worked.
From Docs:
http://php.net/manual/en/function.json-decode.php
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
You should really check if json_decode works, here is an example to demonstrate:
<?php
$badjson = '{bad:"json"}';
$decoded = json_decode($badjson);
if(json_last_error()!==JSON_ERROR_NONE){
echo "Json Decode Failed: ".json_last_error_msg();
}else{
var_dump($decoded);
}
echo "\n---\n";
$goodjson = '{"property":"value"}';
$decoded = json_decode($goodjson);
if(json_last_error()!==JSON_ERROR_NONE){
echo "Json Decode Failed: ".json_last_error_msg();
}else{
var_dump($decoded);
}
See it in action here: http://sandbox.onlinephpfunctions.com/code/3a07e57f4cd01bd63d2945d5e367bbb0a6158195
See PHP Docs: http://php.net/manual/en/function.json-last-error.php
You can use a syntax checker to find the problem with your json e.g. http://jsonlint.com/
A common issue if the json is manually created is failing to wrap properties in double quotes e.g. {property:"value"} is invalid while {"property":"value"} is valid.
Note the reason you have to check json_last_error, and can't rely on NULL meaning it failed is because json_decode('NULL'); would return NULL and that would be correct.
Not sure what is cloud9.
For debug you can try var_dump() function. It will print onto your browser data type and data values, because there could be different type of "nothing". It's not a better way for debugging but a naive one. For better: check debug and breakpoint possibilities in this cloud9.
var_dump() can eat as many arguments as you like, so it's handy to dump everything with php input too to check what comes and how it changes.
I can send json from android to php but i'm unable to extract the data from json object in php. Can anyone help me to that in php?
I tried json_decode($json) to decode the json data.
What I was doing is I'm sending json object from android in get method and receiving the data in php side like this..
<?php
$json=$_GET['data'];
$d_json=json_decode($json) or json_decode($json,true);
?>
but when I was trying to access "$d_json['meal'][0]['name]" or
"$d_json->meal[0]->name" it was showing illegal index.
First I would try to print the $d_json to the screen - to see what is the value it holds.
If $d_json is not empty, but it is not an array (but a string) I would try a little bit of formatting:
$d_json = json_decode( stripslashes( $json ), true );
Then print_r (or var_dump, var_export) the result to see whether it returns an array.
I've done this many times before with various SAAS services, but I can't parse the supposedly JSON responses I'm getting from Blitline image processing's API.
Here's what I do to handle the POST:
$body=#file_get_contents('php://input');
print_r($body);
results=%7B%22original_meta%22%3A%7B%22width
OR
$body=rawurldecode($body);
print_r($body);
results={"original_meta":{"width ...
When I go to print $body->original_meta->width, I get an empty string. You'll realize I didn't json_decode() the $body but that's because that returns an empty string too.
Removing the results= with substr($body, 8) doesn't help either.
Can anyone help?
Expanding on my comment: the POST data is standard x-www-form-urlencoded data so there's no need to access the raw POST data. You can simply access the $_POST array that contains the URL decoded data:
$data = json_decode($_POST['results']);
echo $data->original_meta->width;
Ok this is pretty ugly but it works...
$body = file_get_contents('php://input');
$body=rawurldecode($body);
$body=substr($body, 8);
$body=json_decode($body);
echo $body->original_meta->width; //1936
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.
I want to pass a JSON: {"name":"jason","age":"20} in PHP though POST
In RoR, I can get the two values by using params["name"] & params["age"]
But I don't know how to get them in PHP.
I understand that I can 'translate' the JSON string into associative array by using json_decode but I don't know how to get the JSON string.
In my PHP code, I has tried something like this:
<?php
$json_string = $_POST['params'];
$json_object= json_decode($json_string);
print_r($json_object);
echo $json_object->name;
echo " ";
echo $json_object->age;
?>
Then I has tested the PHP with terminal and I got the correct result
curl -d 'params={"name":"jason", "age":"20"}' xxxx/test_json_decode.php
It works but it seems strange to me, because I didn't set the 'Content-Type: application/json'
Is it the correct way to parse JSON in PHP?
The content-type is only useful in certain cases, such as jquery doing a standard .post where you haven't explicitly told it to expect a json response. A json string is just text, and the content-type is just a clue to the receiver. but you could still send a json string with image/jpeg and still decode it and get a native structure again.
As long as what you pass into json_decode() is a valid JSON string, regardless of the mime-type it was sent with, it'll be decoded into a native structure.