5

How can I access json data within a php-script, which it received via http-post? I'm doing the following on the iOS-side:

NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL];

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/script.php"]];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:data];

[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];

How do I access this data in the php-script? In other words, when I call json_decode(...) in the php-script, what is ...?

Dominik Seibold
  • 2,439
  • 1
  • 23
  • 29
  • A good way to debug this kind of stuff is to `var_dump($_POST)` to a log file and see what you're getting sent. – jprofitt Dec 20 '11 at 14:22
  • I'd suggest finding a basic PHP course first of all to make sure you understand the basics (getting the POST data is fairly basic) of PHP. – Nick Bull Dec 20 '11 at 14:26
  • 4
    Sorry, but $_POST doesn't contain any data, when posting json-data directly. And accessing 'php://input' doesn't seem so basic to me. – Dominik Seibold Dec 20 '11 at 14:35
  • Woah - what's with all the down-votes? – Nick Dec 20 '11 at 15:49

4 Answers4

14

If your are sending your JSON in POST method , It can be received in PHP with the below code

<?php $handle = fopen('php://input','r');
                $jsonInput = fgets($handle);
                // Decoding JSON into an Array
                $decoded = json_decode($jsonInput,true);
?>
Nakkeeran
  • 15,296
  • 1
  • 21
  • 22
  • @nakkeeran, can we always use php://input??? never used it before but it seems to work on my local setup – alex Oct 25 '15 at 13:28
1

The post request when sent using iOS does not works with $_POST. If similar request is issued using js the json in post does works.

Maanas Royy
  • 1,522
  • 1
  • 17
  • 30
  • The correct way of doing it would be to set the header to text/html. If you set the header to application/json the php script just mess it up. – Maanas Royy May 19 '12 at 18:11
0
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody: jsonData];
    [request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];  

This code can be used to send a response

Maanas Royy
  • 1,522
  • 1
  • 17
  • 30
0

In the php script you take the POST data and do

json_decode($data);

and that will give you an object you can work with.

macintosh264
  • 983
  • 2
  • 11
  • 27