Wednesday, August 06, 2014

Gotcha of the Day: Transparently Supporting JSON HTTP POSTS in PHP

I was doing a little back and forth with a client about a web service I was planning to create for them. We were in agreement on pretty much all aspects of the API, but they wanted to deliver the HTTP payload as a JSON string, whereas I preferred x-www-form-urlencoded. Turned out, supporting both wasn't even remotely tricky.

First, I coded up this function:

function json_post_support() {
  if(isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] == 'application/json') {
    $params = json_decode(file_get_contents('php://input'), true);
    foreach($params as $k => $v) {
      $_POST[$k] = $v;
      $_REQUEST[$k] = $v;
    }
  }
}

Then I then stashed this a call to the function at the top of my site's configuration file:

 // Pull in our system includes
 require_once(...);
 require_once(...);
 require_once(...);

 json_post_support();

And that was that.

Within my code I could continue to access $_POST and $_REQUEST, and my client could feel free to send me JSON. Everybody was happy.

No comments:

Post a Comment