0

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)

1
  • 2
    Use curl. Precise the nofollow option. And the url will be in the server response header Commented Oct 5, 2014 at 17:41

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.