To set a custom timeout for DNS resolution in cURL using PHP, you can use the CURLOPT_TIMEOUT
and CURLOPT_DNS_CACHE_TIMEOUT
options.
Here is an example code snippet:
// Create a new cURL resource
$ch = curl_init();
// Set the URL to fetch
curl_setopt($ch, CURLOPT_URL, "https://example.com");
// Set the DNS resolution timeout in seconds
// This timeout includes the time to resolve the DNS and establish the connection
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
// Set the DNS cache timeout in seconds
// This is the time to keep resolved DNS entries in cache
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 1800);
// Execute the cURL request
$response = curl_exec($ch);
// Check for errors
if ($response === false) {
echo 'cURL error: ' . curl_error($ch);
}
// Close cURL resource
curl_close($ch);
// Process the response
// ...
In this code snippet, CURLOPT_TIMEOUT
is set to 5 seconds, which determines the maximum time to wait for both the DNS resolution and TCP connection establishment. If the timeout is reached during these processes, the cURL request will fail.
CURLOPT_DNS_CACHE_TIMEOUT
is set to 1800 seconds (30 minutes), meaning that resolved DNS entries will be kept in cache for that duration, avoiding the need for repeated DNS resolution.