检索重定向网址的内容 |卷曲与上下文

Retrieving contents of re-directed url | curl vs. contexts

本文关键字:上下文 重定向 检索      更新时间:2023-09-26

我正在使用这样的file_get_contents

file_get_contents( $url1 ).

但是,实际网址的内容来自$url 2。

这是一个具体案例:

$url1 = gmail.com
$url2 = mail.google.com

我需要一种方法在PHP或JavaScript中以编程方式抓取$url 2。

我相信

您可以通过创建上下文来做到这一点:

$context = stream_context_create(array('http' =>
    array(
        'follow_location'  => false
    )));
$stream = fopen($url, 'r', false, $context);
$meta = stream_get_meta_data($stream);

$meta应包括(除其他事项外)用于保存重定向 URL 的状态代码和位置标头。如果$meta表示 200,则可以使用以下方法获取数据:

$meta = stream_get_contents($stream)

不利的一面是,当您获得 301/302 时,您必须使用 Location 标头中的 url 再次设置请求。 起泡,冲洗,重复。

如果你想

提取当前的网址,在JS中你可以使用window.location.hostname

我不明白为什么你想要PHPJavaScript。我的意思是。。。他们在处理问题方面有点不同。

假设你想要一个服务器端的PHP解决方案,这里有一个全面的解决方案。代码太多,无法逐字复制,但是:

function follow_redirect($url){
  $redirect_url = null;
  //they've also coded up an fsockopen alternative if you don't have curl installed
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_HEADER, true);
  curl_setopt($ch, CURLOPT_NOBODY, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  curl_close($ch);
  //extract the new url from the header
  $pos = strpos($response, "Location: ");
  if($pos === false){
    return false;//no new url means it's the "final" redirect
  } else {
    $pos += strlen($header);
    $redirect_url = substr($response, $pos, strpos($response, "'r'n", $pos)-$pos);
    return $redirect_url;
  }
}
//output all the urls until the final redirect
//you could do whatever you want with these
while(($newurl = follow_redirect($url)) !== false){
  echo $url, '<br/>';
  $url = $newurl;
}