Basic JSON request/response in PHP

A friend of mine is writing an iOS application which will communicate with a web server. He needed a basic JSON program to test out his code, so I wrote him this:

<?php
if (isset($_REQUEST['json'])) {
  $decoded = json_decode(stripslashes($_REQUEST['json']), TRUE);
  if (is_null($decoded)) {
    $response['status'] = array(
      'type' => 'error',
      'value' => 'Invalid JSON value found',
    );
    $response['request'] = $_REQUEST['json'];
  }
  else {
    $response['status'] = array(
      'type' => 'message',
      'value' => 'Valid JSON value found',
    );
    //Send the original message back.
    $response['request'] = $decoded;
  }
}
else {
  $response['status'] = array(
    'type' => 'error',
    'value' => 'No JSON value set',
  );
  $response['request'] = $_REQUEST['json'];
}
$encoded = json_encode($response);
header('Content-type: application/json');
exit($encoded);

It accepts POST/GET JSON data passed as json, and gives a JSON response. If you save the code as json.php, you'll be able to test it with: http ://example.com/json.php?json={"a":1,"b":2,"c":3,"d":4,"e":5} Which returns:
{"status":{"type":"message","value":"Valid JSON value found"},"original":{"a":1,"b":2,"c":3,"d":4,"e":5}}

Add new comment