Resolving Specific Hosts to Different IPs with cURL
I just recently finished working on a big migration project recently where we are switching from one DNS provider to another. Since it involved a large number of URLs, I needed to make sure once the DNS is switched, all URLs would still work as expected.
To ensure the migration went smoothly, I implemented a few tests, including a crawl script to check the HTTP status codes of the most visited URLs.
In cURL, this is achieved by specifying the --resolve
flag in the format of <host>:<port>:<ip>
. In PHP, you can achieve the same thing by setting the CURLOPT_RESOLVE
option via curl_setopt
, using the same format. In my script, I am looping a set of URLs by letting cURL to resolve it automatically to check the current HTTP status code, then do another check by overriding the host to a different IP.
Only gotcha that I found when writing the script was that even if you instantiate different cURL sessions via curl_init
, once they are added to the same cURL multi handle created with curl_multi_init
, the host resolution doesn’t always work as expected.
Maybe I did something wrong, but I already added a few extra precautions just to be safe like this:
<?php
$ch = curl_init();
curl_setopt( $ch, CURLOPT_DNS_CACHE_TIMEOUT, 0 );
curl_setopt( $ch, CURLOPT_FORBID_REUSE, true );
curl_setopt( $ch, CURLOPT_FRESH_CONNECT, true );