file_get_contents不适用于某些网址

Par*_*xit 8 php curl file-get-contents

file_get_contents在PHP中使用.在下面的代码中,第一个URL工作正常,但第二个不起作用.


$URL = "http://test6473.blogspot.com";
$domain = file_get_contents($URL);
print_r($domain);


$add_url= "http://adfoc.us/1575051";
$add_domain = file_get_contents($add_url);
echo $add_domain;

Run Code Online (Sandbox Code Playgroud)

为什么第二个不起作用的任何建议?

Par*_*xit 12

file_get_contents未检索的URL,因为它们的服务器检查请求是来自浏览器还是来自任何脚本.如果他们从脚本中找到请求,则只会禁用页面内容.

所以我必须提出类似浏览器请求的请求.所以我使用以下代码来获取第二个url内容.对于不同的Web服务器可能会有所不同.因为他们可能会保持不同的检查

即使你为什么不尝试使用以下代码!如果你很幸运,这可能适合你!

function getUrlContent($url) {
    fopen("cookies.txt", "w");
    $parts = parse_url($url);
    $host = $parts['host'];
    $ch = curl_init();
    $header = array('GET /1575051 HTTP/1.1',
        "Host: {$host}",
        'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language:en-US,en;q=0.8',
        'Cache-Control:max-age=0',
        'Connection:keep-alive',
        'Host:adfoc.us',
        'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36',
    );

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);

    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

$url = "http://adfoc.us/1575051";
$html = getUrlContent($url);
Run Code Online (Sandbox Code Playgroud)

谢谢大家的指导.