curl POST format for CURLOPT_POSTFIELDS
To make a POST request with PHP's cURL functions, you can use the CURLOPT_POST option to send POST data.
To make a POST request with PHP's cURL functions, you can use the CURLOPT_POST option to send POST data. The CURLOPT_POSTFIELDS option is used to specify the POST data as a string or array.
Here's an example of how you can use CURLOPT_POST and CURLOPT_POSTFIELDS to make a POST request with PHP's cURL functions:
How to make a POST request with PHP's cURL functions?
<?php
// Set up the cURL request
$ch = curl_init('https://jsonplaceholder.typicode.com/posts');
// Set the request method to POST
curl_setopt($ch, CURLOPT_POST, true);
// Set the POST data as a JSON string
$data = [
'title' => 'foo',
'body' => 'bar',
'userId' => 1,
];
$jsonData = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
// Execute the request
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
// Close the cURL handle
curl_close($ch);
// Do something with the response
echo $response;
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
In this example, CURLOPT_POST is set to true to indicate that the request should be a POST request, and CURLOPT_POSTFIELDS is set to a JSON-encoded string. The Content-Type header is explicitly set to application/json to inform the server about the payload format.
You can also use an array to specify the POST data, like this:
How to make a POST request by using an array to specify the POST data with PHP's cURL functions?
<?php
// Set up the cURL request
$ch = curl_init('https://jsonplaceholder.typicode.com/posts');
// Set the request method to POST
curl_setopt($ch, CURLOPT_POST, true);
// Set the request body data as an array
$data = [
'title' => 'foo',
'body' => 'bar',
'userId' => 1,
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Set the request headers to indicate form-urlencoded data
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
// Execute the request
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
echo 'Error: ' . curl_error($ch);
}
// Close the cURL handle
curl_close($ch);
// Do something with the response
echo $response;In this example, CURLOPT_POSTFIELDS is set to an array containing the POST data. When an array is passed, PHP's cURL automatically encodes it as application/x-www-form-urlencoded key-value pairs, with keys and values separated by an equals sign (=) and pairs separated by ampersands (&).