POSTing parameters to PHP from an iOS app

Recently I ran into an interesting problem on how to POST parameters from an iOS app (I was using AFNetworking for communications) to PHP. Looks like it's quite straightforward for GET requests such that you can easily retrieve parameters with $_GET['parameter_name'].

But for POST it's little complicated. Here's how I did it.

Objective-C :

Here's a code I used to POST parameters to PHP server script for further processing.

I am using AFNetworking-RACExtensions to make network requests

Initialize AFHTTPRequestOperationManager with required parameters and acceptable content types,


AFHTTPRequestOperationManager* manager = [[AFHTTPRequestOperationManager alloc] init];   
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", nil];

Send the request with required parameters


[[[manager] rac_POST:[remote_url] parameters:@{@"value": @"100"}] subscribeNext:^(id x) {
    NSLog(@"Operation succeeded with response %@", [x first]);
} error:^(NSError* error) {
    NSLog(@"Failed with an error %@", [error localizedDescription]);
}];

And here's PHP script to retrieve these values,

PHP


  // Input paylaod received from client
  $handle = fopen("php://input", "rb");
  $post_data = '';
  while (!feof($handle)) {
      $post_data .= fread($handle, 8192);
  }
  fclose($handle); 
  $postDataDictionary = json_decode($raw_post_data, true);

Once you get the hold of $postDataDictionary which holds POSTed parameters, you can safely retrieve its value as follows


$value = $postDataDictionary['value']; // $value = 100. 

Hope this will help someone who is writing an iOS app with PHP as a backend (Of course without any backend framework. If you're using any PHP framework to build a backend, I don't think you have to go through all this PHP boilerplate code)