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
));Written by 蒼時弦や
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#