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

4
  • 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. Commented Dec 20, 2011 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. Commented Dec 20, 2011 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. Commented Dec 20, 2011 at 14:35
  • Woah - what's with all the down-votes? Commented Dec 20, 2011 at 15:49

4 Answers 4

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);
?>
Sign up to request clarification or add additional context in comments.

1 Comment

@nakkeeran, can we always use php://input??? never used it before but it seems to work on my local setup
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.

1 Comment

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

2 Comments

I think. Give it a shot, and let me know
No, I doesn't work with $_POST. By the way, why does this question get so many down-votes?! What's so bad about it?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.