Categories: Development

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 webserver 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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago