What alternative methods, such as cURL, can be used to set a timeout for both connection and data retrieval in PHP?

When making HTTP requests in PHP, it is important to set timeouts for both connection and data retrieval to prevent the script from hanging indefinitely. One way to achieve this is by using cURL, a powerful library for transferring data with URLs. By setting the CURLOPT_TIMEOUT option in cURL, you can specify the maximum amount of time in seconds that the request is allowed to take before it times out.

$url = "https://example.com/api";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Set timeout to 10 seconds for both connection and data retrieval
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

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

curl_close($ch);