3

我正在使用 file_get_contents

file_get_contents( $url1 ).

然而实际 url 的内容来自 $url2。

下面是一个具体案例:

$url1 = gmail.com

$url2 = mail.google.com

我需要一种在 PHP 或 JavaScript 中以编程方式获取 $url2 的方法。

4

3 回答 3

1

如果你想提取当前的 url,在 JS 中你可以使用 window.location.hostname

于 2012-05-24T22:12:11.007 回答
1

我相信你可以通过创建一个上下文来做到这一点:

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

$meta 应该包括(除其他外)状态代码和用于保存重定向 url 的 Location 标头。如果 $meta 指示 200,您可以使用以下方法获取数据:

$meta = stream_get_contents($stream)

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

于 2012-05-24T22:21:48.297 回答
1

我不明白你为什么想要 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;
}
于 2012-05-24T22:26:28.450 回答