Now you can Subscribe using RSS

Submit your Email

Sunday

$_POST array empty? Using JSON with $_POST.

Vishal Shrestha
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.

Vishal Shrestha / Author & Founder

A developer by profession, a born Adventurer. I mainly do Android but like to get my hands dirty with web development and a little bit of Python. I would't rather go on a Trek than a party and you can find me having a few rounds with the heavy bag to let out the steam ;)

For Business info : My Portfolio Site.

0 comments:

Post a Comment

Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha