How to POST JSON data with PHP

How to POST JSON data or a file in PHP including receiving the POST request and saving it to a file.

This is done with the easy to use PHP cURL library.

POST is an HTTP request that the target web server accepts the data stored in its body.

To send a pre-existing JSON file:

<?php
$url = 'https://domain.com/folder/post_data.php';

$data = file_get_contents("file_to_send.json");

$crl = curl_init($url);
curl_setopt($crl, CURLOPT_POST, 1);
curl_setopt($crl, CURLOPT_POSTFIELDS, $data);
curl_setopt($crl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($crl);
echo $result;

To GET and then POST the JSON data:

$url = 'https://domain.com/folder/post_data.php';

$data = json_decode(file_get_contents("https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations"), true);

$crl = curl_init($url);
curl_setopt($crl, CURLOPT_POST, 1);
curl_setopt($crl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($crl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($crl);
echo $result;

The file that receives the POST request and the data (post_data.php):

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $the_file = fopen("thefile.json", 'wb') or die("Unable to open file!");
    fwrite($the_file, json_encode($data, JSON_THROW_ON_ERROR));
    fclose($the_file);
    echo "success";
} else {
    echo "fail";
}

If the request method is a POST, which it will be if coming from the cURL script above this saves the JSON file and outputs “success”. Else “fail” will be outputted.