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. 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:

<?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);

// Close the cURL handle
curl_close($ch);

// Do something with the response
echo $response;

Watch a course Learn object oriented PHP

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 string containing the POST data. The POST data is encoded as key-value pairs, with the keys and values separated by an equals sign (=) and the pairs separated by ampersands (&).

You can also use an array to specify the POST data, like this:

<?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 JSON
$data = [
  'title' => 'foo',
  'body' => 'bar',
  'userId' => 1,
];
$data_json = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);

// Set the request headers to indicate that JSON data is being sent
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Content-Length: ' . strlen($data_json)]);

// Execute the request
$response = curl_exec($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. The keys and values in the array will be automatically encoded as key-value pairs in the POST data.