【发布时间】:2011-05-18 11:05:31
【问题描述】:
我正在使用 file_get_contents() 从站点中获取内容,令人惊讶的是,即使我作为参数传递的 URL 重定向到另一个 URL,它也能正常工作。
问题是我需要知道新的 URL,有没有办法做到这一点?
【问题讨论】:
我正在使用 file_get_contents() 从站点中获取内容,令人惊讶的是,即使我作为参数传递的 URL 重定向到另一个 URL,它也能正常工作。
问题是我需要知道新的 URL,有没有办法做到这一点?
【问题讨论】:
如果您需要使用file_get_contents() 而不是 curl,请不要自动跟随重定向:
$context = stream_context_create(
array(
'http' => array(
'follow_location' => false
)
)
);
$html = file_get_contents('http://www.example.com/', false, $context);
var_dump($http_response_header);
答案灵感来自:How do I ignore a moved-header with file_get_contents in PHP?
【讨论】:
$http_response_header?
$http_response_header中的301位置。
您可以使用 cURL 而不是 file_get_contents() 发出请求。
这样的东西应该可以工作......
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
$l = trim($r[1]);
【讨论】:
一切尽在一个功能中:
function get_web_page( $url ) {
$res = array();
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // do not return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$res['content'] = $content;
$res['url'] = $header['url'];
return $res;
}
print_r(get_web_page("http://www.example.com/redirectfrom"));
【讨论】:
使用裸file_get_contents 的完整解决方案(注意输入输出$url 参数):
function get_url_contents_and_final_url(&$url)
{
do
{
$context = stream_context_create(
array(
"http" => array(
"follow_location" => false,
),
)
);
$result = file_get_contents($url, false, $context);
$pattern = "/^Location:\s*(.*)$/i";
$location_headers = preg_grep($pattern, $http_response_header);
if (!empty($location_headers) &&
preg_match($pattern, array_values($location_headers)[0], $matches))
{
$url = $matches[1];
$repeat = true;
}
else
{
$repeat = false;
}
}
while ($repeat);
return $result;
}
请注意,这仅适用于 Location 标头中的绝对 URL。如果您需要支持相对 URL,请参阅
PHP: How to resolve a relative url.
例如,如果您使用answer by @Joyce Babu 中的解决方案,请替换:
$url = $matches[1];
与:
$url = getAbsoluteURL($matches[1], $url);
【讨论】:
我用get_headers($url, 1);
在我的情况下,get_headers($url, 1)['Location'][1];中的重定向网址
【讨论】: