How to make POST requests in JSON with PHP and handle the request
Let’s imagine having to create, through JSON in PHP, a data transfer connection from one server to another. For example, we can create a service that communicates geographical coordinates to an address.
The code below is the construction of a POST call, of type JSON, which communicates a token (invented) for the use of a service, and a location expressed in geographical coordinates.
<?php
$url = "https://www.selectallfromdual.com/services/ecc..."
$data = ['token' => '213132131321', 'location' => '99.000000,99.000000'];
fetch($url,
{method: 'POST',
headers: {'Content-Type': 'application/json' },
body: JSON.stringify($data)
});
?>
The service that receives the POST request, having the global variable $_POST empty, will have to use the input stream to be able to receive the data and process the request
<?php
header('Content-Type: application/json');
$post_data = json_decode(file_get_contents('php://input'), true);
$token = $post_data['token'];
$location = $post_data['location'];
?>