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" => "[email protected]"
];
// Convert the PHP array into a JSON format
$payload = json_encode[$data];
// Initialise new cURL session
$ch = curl_init['//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
//
PreviousNextI'm trying to send a get request using PHP anycodings_json and curl to retrieve a JSON array using rest anycodings_json API request works fine when I test it by anycodings_json entering the address in chrome address bar anycodings_json or even in command prompt or PowerShell , anycodings_json but it returns an empty array using PHP curl anycodings_json , here is my code