How to Send (POST) JSON Data with PHP cURL

Posted on August 31, 2020 at 11:14 am

Example PHP code to send (via HTTP POST) JSON data to an URL:

$data = array(
    "username" => "admin",
    "password" => "password",
$curl = curl_init("");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLINFO_HEADER_OUT, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json');
$output = curl_exec($curl);

The PHP receiver script should look like this:

@header('Content-Type: application/json; charset=utf-8');
$json = file_get_contents('php://input');
$array = json_decode($json, true);
$username = $array['username'];
$password = $array['password'];
$result = array();
$result['status'] = "OK";
echo json_encode($result);

Receive updates via email

Other Posts

Updated Posts