DEV Community

Discussion on: Catch and parse JSON Post data in PHP

Collapse
 
mrcodekiddie profile image
Muthu Kumar • Edited

Just In Case, If anyone need this

<?php
// Only allow POST requests

$response=new stdClass(); //you may get a warning , otherwise . 
header('Content-Type: application/json'); //gonna send everything as JSON response.. so, anyways

if (strtoupper($_SERVER['REQUEST_METHOD']) != 'POST') {
  http_response_code(405);
  $response->status="failed";
  $response->message="Method Not Allowed";
  echo json_encode($response);
  exit();
}

// Make sure Content-Type is application/json 
$content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
if (stripos($content_type, 'application/json') === false) {
  $response->status="failed";
  $response->message="Content-Type must be application/json";
  http_response_code(415);
  echo json_encode($response);
  exit();
}

// Read the input stream
$request_body = file_get_contents("php://input");

// Decode the JSON object
$data = json_decode($request_body, true);

// Throw an exception if decoding failed
if (!is_array($data)) {
  $response->status="error";
  $response->message="Invalid JSON";
  http_response_code(400);
  echo json_encode($response);
  exit();  
}
Enter fullscreen mode Exit fullscreen mode