虽然OP想避免cURL
,这是最好的时候,它可以使用它。下面是它具有以下优点
- 使用卷曲为所有繁重的解决方案,因此可与HTTPS
- COPES与返回下套管
location
头名(包括xaav和webjay的答案不处理这个)服务器
- 允许你控制你想有多深,你放弃
这里之前去的功能:
function findUltimateDestination($url, $maxRequests = 10)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, $maxRequests);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
//customize user agent if you desire...
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Link Checker)');
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
$url=curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close ($ch);
return $url;
}
下面是一个更详细的版本,它允许您检查重定向链而不是让curl跟着它。
function findUltimateDestination($url, $maxRequests = 10)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
//customize user agent if you desire...
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Link Checker)');
while ($maxRequests--) {
//fetch
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
//try to determine redirection url
$location = '';
if (in_array(curl_getinfo($ch, CURLINFO_HTTP_CODE), [301, 302, 303, 307, 308])) {
if (preg_match('/Location:(.*)/i', $response, $match)) {
$location = trim($match[1]);
}
}
if (empty($location)) {
//we've reached the end of the chain...
return $url;
}
//build next url
if ($location[0] == '/') {
$u = parse_url($url);
$url = $u['scheme'] . '://' . $u['host'];
if (isset($u['port'])) {
$url .= ':' . $u['port'];
}
$url .= $location;
} else {
$url = $location;
}
}
return null;
}
由于此函数处理重定向链的例子,但其他人不这样做,试试这个:
echo findUltimateDestination('http://dx.doi.org/10.1016/j.infsof.2016.05.005')
在写这篇文章的时候,这涉及到4个请求,与Location
混合和location
标题涉及。
有*多个*'位置:'在一个响应头? – Tomalak 2010-09-26 18:08:41
get_headers确实会根据defualt自动执行重定向,所以我得到了多个'Location:'头文件。我想要的是完整的最终URL(http://domain.test/final/page.ext?attr ...) – Weboide 2010-09-26 18:11:02
我不明白这个问题:( – Stewie 2010-09-26 18:15:37