How can POST data be effectively passed using cURL in PHP?

To effectively pass POST data using cURL in PHP, you can use the CURLOPT_POSTFIELDS option to set the data to be sent in the POST request. This option expects a string containing the data in key-value pairs. You can also set the CURLOPT_POST option to true to indicate that the request is a POST request.

<?php
// Initialize cURL session
$ch = curl_init();

// Set the URL to which the POST request will be sent
curl_setopt($ch, CURLOPT_URL, 'https://example.com/api');

// Set the request method to POST
curl_setopt($ch, CURLOPT_POST, true);

// Set the POST data to be sent
$postData = array(
    'key1' => 'value1',
    'key2' => 'value2'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));

// Execute the POST request
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Handle the response
echo $response;
?>