PHP: Get link address from redirected URL

2019-09-07 14:15发布

How can I get the link address after a URL has been redirected?

Take for example this URL: http://www.boligsiden.dk/viderestilling/992cff55882a40f79e64b0a25e847a69

How can I make a PHP script echo the final URL? (http://www.eltoftnielsen.dk/default.aspx?side=sagsvisning&AutoID=125125&DID=140 in this case)

2条回答
我想做一个坏孩纸
2楼-- · 2019-09-07 14:26

use this

<?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; 
?>

enter link description here

查看更多
爷、活的狠高调
3楼-- · 2019-09-07 14:29

Note: The following solution isn't ideal for high traffic situations.

$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];
}

Here's what happens: file_get_contents() redirects and downloads the target website but writes the original response header into $http_response_header.

the preg_match tries to find the first "Location: x" match and returns it.

查看更多
登录 后发表回答