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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago