PHP:从重定向的URL获取链接地址
问题描述:
如何在重定向URL后获取链接地址?PHP:从重定向的URL获取链接地址
就拿这个网址:http://www.boligsiden.dk/viderestilling/992cff55882a40f79e64b0a25e847a69
我怎样才能让一个PHP脚本回声最终网址是什么? (在这种情况下http://www.eltoftnielsen.dk/default.aspx?side=sagsvisning&AutoID=125125&DID=140)
答
注:以下解决方案是不理想的流量大的场合。
$url = 'http://www.boligsiden.dk/viderestilling/992cff55882a40f79e64b0a25e847a69';
file_get_contents($url);
preg_match('/(Location:|URI:)(.*?)\n/', implode("\n", $http_response_header), $matches);
if (isset($matches[0]))
{
echo $matches[0];
}
这里发生了什么:file_get_contents()函数重定向和下载目标网站,但原来的响应头写入$ http_response_header。
preg_match试图找到第一个“Location:x”匹配并返回它。
答
使用本
<?php
$name="19875379";
$url = "http://www.ikea.co.il/default.asp?strSearch=".$name;
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$header = curl_exec($ch);
$redir = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
//print_r($header);
$x = preg_match("/<script>location.href=(.|\n)*?<\/script>/", $header, $matches);
$script = $matches[0];
$redirect = str_replace("<script>location.href='", "", $script);
$redirect = "http://www.ikea.co.il" . str_replace("';</script>", "", $redirect);
echo $redirect;
?>
使用卷曲。精确的nofollow选项。该网址将位于服务器响应标题中 – 2014-10-05 17:41:25