How to Post JSON Data Using cURL in PHP
Posted on: March 06, 2021 by Ariessa Norramli
In this article, you will learn how to post JSON data using cURL in PHP. cURL
command is usually used to transfer data to and from a server.
Post JSON Data Using cURL
In order to post JSON data using cURL, you can use the curl_init()
method, curl_setopt()
method, curl_exec()
method, and curl_close()
method.
$data = array(
"name" => "John",
"email" => "john@test.com"
);
// Convert the PHP array into a JSON format
$payload = json_encode($data);
// Initialise new cURL session
$ch = curl_init('https://api.creativecommons.engineering/v1/auth_tokens/register');
// Return result of POST request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Get information about last transfer
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
// Use POST request
curl_setopt($ch, CURLOPT_POST, true);
// Set payload for POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set HTTP Header for POST request
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload))
);
// Execute a cURL session
$result = curl_exec($ch);
// Close cURL session
curl_close($ch);
Note: The curl_init()
method functions by initialising a new cURL session. The curl_setopt()
method functions by setting options for a cURL session handle. The curl_exec()
method functions by executing a cURL session. The curl_close()
method functions by closing a cURL session to free up resources.
Share on social media
//