$_POST array empty? Using JSON with $_POST.

Despite its name, the $_POST array won’t always contain your POST data and can be easily found empty.
It’s because PHP only parses a POST payload automatically when it has a content type of application/x-www-form urlencoded or multipart/form-data.
let’s take an example. Assume that we make a server request with a jQuery.ajax() call as follows:

$.ajax({

    url: 'http://www.somesite.com/some/path',

    method: 'post',

    data: JSON.stringify({a: '1', b: '2'}),

    contentType: 'application/json'



});

Now if on the server side, we  dump the $_POST array:

var_dump($_POST);

Surprisingly, the result will be:

array(0) { }

It’s because the content type is json, not multipart/form-type.

If we want to achieve this, we need to manually decode the JSON data and override the $_POST variable like this:

// php

$_POST = json_decode(file_get_contents('php://input'), true);


Now if we dump the $_POST array, we can see that it includes the POST payload;

array(2) { [“a”]=> string(1) “a” [“b”]=> string(1) “b” }

If you have any questions, do comment of message me.

Don’t miss these tips!

We don’t spam! Read our privacy policy for more info.

Sharing is caring!

1 thought on “$_POST array empty? Using JSON with $_POST.”

Leave a Comment

Your email address will not be published.