Using CURL to access certain IP of a Domain
Something I needed to do recently was get the contents of a certain url of a certain domain name, for each of the IP addresses associated with that domain name. In other words, there was a domain we shall call www.test-domain.com, which was hosted on 5 different servers, with IPs 1.2.3.100 through 1.2.3.104. I wanted to automate the getting of the contents of www.test-domain.com/file-name.php on each of these servers. I could set my hosts file of course, and point at each server, blah blah blah, but this had to be automated, for sanity.
The php curl library is fully awesome, but personally I find this page to be the most useful. There are surprisingly few examples of this anywhere on the web…just try googling this topic and you get nothing at all relevant!
The solution is simple enough, but believe me it won’t be easy to find on the web – thanks to a certain work colleague for the expert advice on this! Basically you need to inject a header using CURLOPT_HTTPHEADER, and then use CURLOPT_URL with the actual IP address.
For example:
$ch = curl_init();
$headers = array("Host: www.test-domain.com");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, "http://1.2.3.100/file-name.php");
curl_exec($ch);
That’s the engine of it, a very neat little solution!
//