代码之家  ›  专栏  ›  技术社区  ›  Krishna Mohan Sarath VK

file_get_contents不适用于某些域

  •  0
  • Krishna Mohan Sarath VK  · 技术社区  · 10 年前

    作为要求的一部分,我需要确定域是否已停放。由于没有有效的方法来发现这一点,我将检查DOM中的短语,如“购买此域”、“可能出售”。。等

    我找到了一些可以通过浏览器访问的停放域,但无法使用 file_get_contents .

    实例

    $url = 'http://buythisdomain.com/'
    $get = file_get_contents($url);
    

    对于以上内容,在输出时得到以下消息。

    警告:file_get_contents( http://buythisdomain.com/ ):无法打开流:HTTP请求失败!

    但可以通过浏览器访问相同的URL fopen 方法也是,但结果相同。有没有办法实现这一点?

    1 回复  |  直到 10 年前
        1
  •  5
  •   Brain Foo Long    10 年前

    许多站点(不仅仅是停放的域)使用某种机制来阻止没有有效浏览器标头的基本请求。

    尝试使用流上下文来发送所需的标头,就像这样的浏览器

    $url = "http://buythisdomain.com/"
    $context = stream_context_create(array(
        'http' => array(
            'method' => "GET",
            'header' =>
                "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" .
                "Accept-Language: en-US,en;q=0.8\r\n".
                "Keep-Alive: timeout=3, max=10\r\n",
                "Connection: keep-alive",
            'user_agent' => "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11",
            "ignore_errors" => true,
            "timeout" => 3
        )
    ));
    file_get_contents($url, false, $context);