【问题标题】:Why is curl links redirecting through localhost?为什么 curl 链接通过 localhost 重定向?
【发布时间】:2020-09-04 00:53:34
【问题描述】:

现在,我有当前的 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 页面,其中包含与搜索体育新闻相对应的搜索结果。虽然,当您尝试单击这些链接中的任何一个时,它会将您重定向到“localhost:/--url--”。如何防止 curl 重定向到 localhost 而是重定向到实际站点?

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

【问题讨论】:

  • 它可能尊重它来自的 url,它是您的本地主机。这不是你想要的吗?当然这是你想要的。从 localhost 进行“测试”并不少见。当您希望它重定向到“真实”站点时,即通过上传到真实站点来上线。
  • 有什么办法可以防止在本地主机上发生这种情况并使其正常工作吗?
  • 一个人有什么理由去拜访你当地的主人吗?检查您申请的 api 信用。他们可能会列出本地主机。我的本地主机与您和其他所有人的不同。只有您的计算机/开发环境知道本地主机是您的机器............(当然,除非您是静态 IP?此时您的下载文件夹 确实 看起来很有趣。谁这些人在你的图片文件夹中吗?)
  • 嗨,Sid,您是否考虑将 $result 的一部分粘贴到 URL 中?只是一个想法。

标签: php google-chrome curl


【解决方案1】:

发生这种情况是因为 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, 0, 1) === '/') {
        
        // Prepend Google domain
        $link->setAttribute('href', "https://google.com/" . $relativePath);
    }
}

echo $dom->saveHTML();

【讨论】:

  • 我不知道为什么,但是每次我运行这段代码时,我都会在 loadXML($result) 行中遇到错误:
  • DOMDocument::loadXML(): StartTag: Entity 中的元素名称无效
  • 它说:警告:DOMDocument::loadXML(): Extra content at the end of the document in Entity
  • @SidNutthi,这是由于 HTML 错误,您可以通过在所有其他代码之前将此行添加到顶部来解决此问题: libxml_use_internal_errors(true);我已经更新了答案
  • 非常感谢!这奏效了,我什至不能告诉你我有多高兴。你真的给了我很大的帮助,谢谢@Cyril Graze。
猜你喜欢
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 2011-07-07
  • 2011-10-29
  • 2019-04-22
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
相关资源
最近更新 更多