If data is send with a traditional multipart/form-data
or application/x-www-form-urlencoded
JSON data in FORM values will be automatically be converted and available in its corresponding $_POST
, $_REQUEST
or $_GET
global.
This scenario is handle fairly simple with:
<?
$data = @json_decode($_POST['json_field']);
Thats not the case with json data sent as "application/json"
.
<?
$data = @json_decode(($fp = fopen('php://input', 'r')) !== false ? stream_get_contents($fp) : "{}", true);
$_POST = array_merge($_POST, (array) json_decode(file_get_contents('php://input')));
As of PHP 5.6 you have the global variable $HTTP_RAW_POST_DATA
to get the raw POST data.
This example is a failsafe handling of json data that will always return an associative array. If no valid data is found an empty array is returned.
<?
if($_SERVER['REQUEST_METHOD'] != 'POST') return [];
//optional check of a "application/json" as CONTENT_TYPE
$mime = isset($_SERVER["CONTENT_TYPE"]) ? strtolower(trim($_SERVER["CONTENT_TYPE"])) : '';
if($mime != 'application/json') return [];
//read input or fake it
$payload = ($fp = fopen('php://input', 'r')) !== false ? stream_get_contents($fp) : "{}";
$data = @json_decode($payload, true);
if(!is_array($data)) return [];
return $data;
<?
$data = @json_decode($json, true);
if(!is_array($data)){
//json was not converted...
}
Using the function json_last_error()
added since 5.3.0:
<?
$data = @json_decode($json, true);
$err = json_last_error();
if($err != JSON_ERROR_NONE){
//json was not converted...
}
An example sending JSON data with JQuery that is available in your $_POST
.
var data = {};
data.json = JSON.stringify(record);
var url = "https://mysite.com/myscript.php";
//call my php
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json' //expects json data in response
}).done( function( data ){
}).fail( function( data ){
});