PHP cURL consistently taking 15s to resolve DNS

前端 未结 3 1915
遇见更好的自我
遇见更好的自我 2021-01-02 11:53

I\'m running PHP on a CentOS virtual machine under MacOS X, and any cURL request consistently takes 15s to run:

$c =          


        
相关标签:
3条回答
  • 2021-01-02 12:19

    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.

    0 讨论(0)
  • 2021-01-02 12:31

    There may be something wrong in your system, but I find a way to work around it.

    $urldata = parse_url($yourUrl);  
    $host = $urldata['host'];  
    $ip = gethostbyname($host);  
    $new_Url_dns_resolved = str_replace($host,$ip,$yourUrl);  
    //call the dns resolved url instead of the original url  
    $c = curl_init($new_Url_dns_resolved);
    
    0 讨论(0)
  • 2021-01-02 12:33

    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);
    
    0 讨论(0)
提交回复
热议问题