php - file_get_contents 不适用于某些网址

标签 php curl file-get-contents

我在 PHP 中使用 file_get_contents。在下面的代码中,第一个 URL 工作正常,但第二个 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;

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

最佳答案

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

谢谢大家的指导。

关于php - file_get_contents 不适用于某些网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17363545/

相关文章:

php - 在 Laravel 中将依赖参数传递给 App::make() 或 App::makeWith()

bash - 在 bash 中从 txt 文件中多次读取(线程)

authentication - 通过私有(private)账户从 Netflix 拉取数据

php - HTTP 请求失败! HTTP/1.1 503 服务暂时不可用

php - 文件获取内容(): stream does not support seeking PHP

php - 表锁失败

php - 返回 ajax 结果作为全局整型变量

php - PHP警告:mysqli_num_rows()和数据库创建

curl - PHP Curl 设置 header 来源

php - scraper php 返回空白页