Kişisel web tasarım ve kodlama blogu. Web tasarımı ve kodlama araçları ile ilgili bilgiler ve yardımcı dökümanlar.

Kod yazmak sanattır...

gokhankr.com

Blogger tarafından desteklenmektedir.

Getting $_REQUEST (like POST and GET) as JSON with PHP


 

JSON is the most practical and fastest way to get data. PHP provides encode and decode feature for JSON object. However, you cannot directly fetch data as application-json.

That's why you can't fetch data with the JSON standard over $_GET and $_POST. We will use the input that PHP provides for I/O to get the data.


file_get_contents('php://input')

Now let's expand this a little more and assume that the incoming data is JSON.


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

The above process will take the data when we receive JSON data and convert it to PHP Array, and if the incoming data does not come as JSON, it will return null. So we can now try this process on a Router.


function getJSON()
{
    $jsonData = json_decode(file_get_contents('php://input'), true);
    return $jsonData ?? [];
}

Now you can get the data as JSON via getJSON() just as we get the data via $_POST and $_GET.

If you want, we can also define and use the data globally as we receive it via $_POST or $_GET. For this:


// index.php
$jsonData = json_decode(file_get_contents('php://input'), true);
$GLOBALS['_JSON'] = $jsonData;

//user.php
if (isset($_JSON['userLogin'])) {
    /* ... */
}

In this way, you can define $_GLOBALS on your requested page and use it like $_POST on any page you want. That's all I'm going to tell you in detail about "Getting JSON requests with PHP". Thanks.