【发布时间】:2010-12-13 20:58:57
【问题描述】:
我正在使用 curl 让 php 向某个网站发送一个 http 请求,并将 CURLOPT_FOLLOWLOCATION 设置为 1,以便它遵循重定向。那么,我怎样才能知道它最终被重定向到哪里?
【问题讨论】:
我正在使用 curl 让 php 向某个网站发送一个 http 请求,并将 CURLOPT_FOLLOWLOCATION 设置为 1,以便它遵循重定向。那么,我怎样才能知道它最终被重定向到哪里?
【问题讨论】:
如果你不需要最终的身体,你可以这样做:
设置CURLOPT_HEADER 和CURLOPT_NOBODY。应返回标头“Location”并将包含新的 url。然后根据需要使用新的 url 执行请求。
【讨论】:
你可以这样做:
curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // returns the last effective URL
【讨论】:
$ch = curl_init( "http://websitethatredirects.com" );
$curlParams = array(
CURLOPT_FOLLOWLOCATION => true,
);
curl_setopt_array( $ch, $curlParams );
$ret = curl_exec( $ch );
$info = curl_getinfo( $ch );
print $info['url'];
这将显示您最终被重定向到的 URL。
【讨论】:
测试这个sn-ps的代码。它对我来说很好:
$urls = array(
'http://www.apple.com/imac',
'http://www.google.com/'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
foreach($urls as $url) {
curl_setopt($ch, CURLOPT_URL, $url);
$out = curl_exec($ch);
// line endings is the wonkiest piece of this whole thing
$out = str_replace("\r", "", $out);
// only look at the headers
$headers_end = strpos($out, "\n\n");
if( $headers_end !== false ) {
$out = substr($out, 0, $headers_end);
}
$headers = explode("\n", $out);
foreach($headers as $header) {
if( substr($header, 0, 10) == "Location: " ) {
$target = substr($header, 10);
echo "[$url] redirects to [$target]<br>";
continue 2;
}
}
echo "[$url] does not redirect<br>";
}
【讨论】: