尽管有 FOLLOWLOCATION,但仍使用 cURL 获取 301

2024-04-29

尽管使用了 FOLLOWLOCATION 和 MAXREDIRS,我还是收到了 301 错误。 我不知道该怎么做,我尝试了一切我能做的:HEADER为0,FOLLOWLOCATION为1,MAXREDIRS为30,多次更改USERAGENT,单独使用COOKIEFILE,然后使用COOKIEJAR,但什么也没有。

最奇怪的部分是:我试图抓取的同一个网站并没有为其他页面提供 301,而只是为某些页面提供 301。有任何想法吗??

function curl_start($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.4");
curl_setopt($ch, CURLOPT_REFERER, "http://google.com/");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
$html = curl_exec($ch);
curl_close($ch);
return $html;
}

除非您在安全模式下运行 php,否则它应该可以工作。但即便如此,对于你的情况来说这也不是问题。

不管怎样,试试这个。

<?php
function curl_redirect_exec($ch, &$redirects, $curlopt_header = false) {
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 301 || $http_code == 302) {
        list($header) = explode("\r\n\r\n", $data, 2);
        $matches = array();
        preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
        $url = trim(array_pop($matches));
        $url_parsed = parse_url($url);
        if (isset($url_parsed)) {
            curl_setopt($ch, CURLOPT_URL, $url);
            $redirects++;
            return curl_redirect_exec($ch, $redirects);
        }
    }
    if ($curlopt_header)
        return $data;
    else {
        list(,$body) = explode("\r\n\r\n", $data, 2);
        return $body;
    }
}
?>

SRC: http://www.php.net/manual/en/function.curl-setopt.php#95027 http://www.php.net/manual/en/function.curl-setopt.php#95027

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尽管有 FOLLOWLOCATION,但仍使用 cURL 获取 301 的相关文章

随机推荐