首页 > 解决方案 > Php Curl 不能只在一个网站上工作

问题描述

我有一个非常奇怪的错误。我需要使用 cURL 访问这个网站:http : //sub.example.com/。从本地主机我没有问题,如果我从命令行或浏览器使用 cURL 访问网站。

我在我的 Siteground 服务器上使用此代码:

<?php 


    $url="http://sub.example.com/";
    $agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt($ch, CURLOPT_URL,$url);

    $result=curl_exec($ch);
    var_dump($result);


    ?>

我得到$result = false

如果我使用 Try / Catch 我得到:Curl failed with error #6: Could not resolve host

我还尝试将 $url 替换为另一个网站的 url,它始终有效(http 和 https,域和子域,在我的服务器和外部)!

我已经花了一天时间试图解决这个问题,请帮助我!

提前谢谢你,卢卡

标签: phpcurl

解决方案


根据googledns,sub.example.com不存在。

$ nslookup sub.example.com 8.8.8.8
*** google-public-dns-a.google.com can't find sub.example.com: Non-existent domain
Server:  google-public-dns-a.google.com
Address:  8.8.8.8

它在 localhost 上为您工作的事实意味着您有一个奇怪的 DNS,或者可能在您的hosts 文件中有一个条目,而您的 Siteground 服务器没有。

无论如何,Curl failed with error #6: Could not resolve host这意味着服务器的 dns 找不到sub.example.com,但幸运的是,如果您知道要连接的 ip,则可以完全绕过 DNS,而是编写:

curl_setopt($ch, CURLOPT_URL,'http://93.184.216.34/');
curl_setopt($ch,CURLOPT_HTTPHEADER,array('Host: sub.example.com'));

(还有一个更正确的 curlopt 来告诉 curl 哪个 ip 与哪个域一起使用,但是这个名字现在让我无法理解,而且 iirc、php 还没有添加对它的官方支持,所以你必须使用它的魔法值,而不是定义的名称,但手动设置Host:标题还是很容易的)


推荐阅读