PHP cURL consistently taking 15s to resolve DNS

The problem was an IPv6 lookup failing on my machine. The solution:

Changed /etc/resolv.conf to:

nameserver 8.8.8.8
nameserver 8.8.4.4

After rebooting, resolv.conf got overwritten, so adding this line to /etc/sysconfig/network-scripts/ifcfg-eth0 (which was using BOOTPROTO=dhcp) fixed the problem:

PEERDNS=no

And everything now works like a charm.

As an alternative, if you experience this problem on a server on which you can not change the configuration, configure cURL this way:

curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

With PHP 7.1.32 installed with brew on macos, I got exactly this problem. file_get_contents and curl do not use the same DNS.

Like @schumyxp said, you can resolve manually first:

<?php
$ip = gethostbyname("XXXXX.infra");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://" . $ip);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: XXXXX.infra'));

BTW it's may be a good to force an IP instead of rely on a resolver.

Tags:

Php

Curl