为什么curl链接通过localhost重定向?

问题描述

现在,我拥有当前的PHP代码

<?PHP 

include('simple_html_dom.PHP');

# set up the request parameters
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://www.google.com/search?q=sport+news');
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); 
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_MAXREDirs,0);

$result = curl_exec($curl);
curl_close($curl);

echo $result;
?>

运行此代码时,它将返回一个Google页面,其中包含与搜索体育新闻相对应的搜索结果。虽然,当您尝试单击任何一个theese链接时,它会将您重定向到“ localhost:/-url--”。如何防止curl重定向到本地主机,而是重定向到实际站点

我目前正在使用wampserver进行测试。

解决方法

发生这种情况是因为Google的结果页面在链接中使用了相对URL。

<a href="/url?q=https://www.bbc.co.uk/sport/43634915&amp;sa=U&amp;ved=2ahUKEwjX (...)

请注意,href开头为:/,而不是href="https://foobar.com/url?q=之类的域。

因此,这些链接将使用提供结果的页面的主机名。

在单击结果时得到localhost的原因是,您正在从本地主机提供此代码。

一种解决方案可能是使用DOMDocument PHP扩展来解析链接,并添加一个主机名,以便结果链接是绝对的,而不是相对的。

例如:

// Ignore HTML errors
libxml_use_internal_errors(true);

// Instantiate parser
$dom = new DOMDocument;

// Load HTML into DOM document parser
$dom->loadXML($result);

// Select anchor tags
$books = $dom->getElementsByTagName('a');

// Iterate through all links
foreach ($links as $link) {

    // Get relative link value
    $relativePath = $link->getAttribute('href');

    // Check if this is a relative link
    if (substr($relativePath,1) === '/') {
        
        // Prepend Google domain
        $link->setAttribute('href',"https://google.com/" . $relativePath);
    }
}

echo $dom->saveHTML();