How can cURL be used to improve the functionality of HTTP POST requests in PHP?

cURL can be used in PHP to improve the functionality of HTTP POST requests by providing more control and flexibility compared to using traditional methods like file_get_contents or fopen. cURL allows you to set custom headers, handle redirects, and easily handle authentication. This can be particularly useful when working with APIs or sending data to remote servers.

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['key' => 'value']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL session
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Handle response
if ($response === false) {
    echo 'cURL error: ' . curl_error($ch);
} else {
    echo 'Response: ' . $response;
}