将JSON从iOS发布到PHP

I've been trying to send JSON data from an iOS app to a mySQL database via a php page. For some reason, my POST data is not available in the php page.

- (IBAction)jsonSet:(id)sender {   
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"firstvalue", @"firstkey", @"secondvalue", @"secondkey", nil];
    NSData *result =[NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    NSURL *url = [NSURL URLWithString:@"http://shred444.com/testpost.php"];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", jsonRequestData.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonRequestData];

    NSURLResponse *response = nil;
    NSError *error = nil;

    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

I know the php page gets called, and writing to the database is confirmed,

The first couple of lines in my php file grab the POST data

<?php
// Put parameters into local variables
$email = $_POST["firstkey"];
...

but for some reason, $email is also an empty string. I have a feeling the problem is in the iOS code, because I can use APIkitchen.com to test my page and I can confirm it works (only if I exclude the Content-type and Content-Length fields)

PHP does not decode JSON POST body to $_POST array (so you can't use $email = $_POST["firstkey"];). You need to extract incoming data to array (or object). Lines of code for you PHP-file:

$jsonString = file_get_contents('php://input');
$jsonArray = json_decode($json_string, true);

$jsonArray will represent the JSON structure you sent.

What seemed to work was this:

$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
// Decoding JSON into an Array
$decoded = json_decode($jsonInput,true);

There is a small typo in Valera's answer

$jsonString = file_get_contents('php://input');
$jsonArray = json_decode($jsonString, true);

$email = $jsonArray('firstkey');

this is what worked for me:

$jsonString = file_get_contents('php://input');
$jsonArray = json_decode($jsonString, true);

// with [] instead of ()
$email = $jsonArray['firstkey']; 
<?php

$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$decoded = json_decode($jsonInput,true);
print_r($decoded['firstkey']);

?>