file_get_contents 不适用于某些域

file_get_contents not working for some domains

作为要求的一部分,我需要查明域是否已停放。由于没有有效的方法来找出这一点,我将检查 DOM 中是否有 "Buy this domain"、"may be for sale".. 等短语

我发现了一些可以通过浏览器访问的托管域,但无法使用 file_get_contents.

例子

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

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

Warning: file_get_contents(http://buythisdomain.com/): failed to open stream: HTTP request failed!

但能够通过 browser.I 访问相同的 URL 也尝试了 fopen 方法,但结果相同。有什么办法可以实现吗?

许多站点,不仅是托管域,还使用某种机制来阻止没有有效浏览器的基本请求 headers。

尝试使用发送所需内容的流上下文 headers 像这样的浏览器

$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);