Last Updated: September 09, 2019
·
15.64K
· elct9620

POST JSON data to PHP

My friend discuss about why AngularJS send POST to PHP but it can't using $_POST to receive data.

I find the answer, because PHP default didn't json_decode the content-type which is application/json so the $_POST will not show anything.

This is a simple code to check content-type and select a better method to parse the data.


<?php

$contentType = explode(';', $_SERVER['CONTENT_TYPE']); // Check all available Content-Type
$rawBody = file_get_contents("php://input"); // Read body
$data = array(); // Initialize default data array

if(in_array('application/json', $contentType)) { // Check if Content-Type is JSON
  $data = json_decode($rawBody); // Then decode it
} else {
  parse_str($data, $data); // If not JSON, just do same as PHP default method
}

header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array( // Return data
  'data' => $data
));