What are some best practices for setting timeouts when making HTTP POST requests in PHP?

When making HTTP POST requests in PHP, it is important to set timeouts to prevent the script from hanging indefinitely if the server does not respond. This ensures that the script does not waste resources waiting for a response that may never come. Setting appropriate timeouts can help improve the overall performance and reliability of your application.

// Set timeout for HTTP POST request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Set timeout to 10 seconds
$response = curl_exec($ch);
curl_close($ch);

if ($response === false) {
    // Handle timeout or connection error
    echo 'Error: ' . curl_error($ch);
} else {
    // Process the response
    echo $response;
}