What are some best practices for handling HTTP POST responses in PHP when using cURL?

When making HTTP POST requests using cURL in PHP, it is important to handle the response properly to ensure that the request was successful and to process any data returned by the server. One common practice is to check the HTTP status code in the response header to determine if the request was successful. Additionally, you can use cURL functions like `curl_getinfo()` and `curl_error()` to gather more information about the response.

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

// Set cURL options for POST request
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['param1' => 'value1', 'param2' => 'value2']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

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

// Check for cURL errors
if(curl_errno($ch)){
    echo 'cURL error: ' . curl_error($ch);
}

// Get HTTP status code
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// Close cURL session
curl_close($ch);

// Process response based on HTTP status code
if($http_status == 200){
    // Request was successful, process response data
    echo $response;
} else {
    // Request failed, handle error
    echo 'HTTP error: ' . $http_status;
}