Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the url, a given url redirects to

Tags:

php

web

I mine data from rss links and get a bunch of urls like:

http://feedproxy.google.com/~r/electricpig/~3/qoF8XbocUbE/

.... and if I access the links in my web browser, I am redirected to something like:

http://www.electricpig.co.uk/stuff.

Is there a way in php to write a function that, when given a url "a" that redirects the user to an url "b", returns you the url "b" ?

like image 307
fleurette Avatar asked Sep 05 '12 12:09

fleurette


2 Answers

Here you go:

function getRedirect($oldUrl) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $oldUrl);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    $newUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    return $newUrl;
}

The function requires cURL, and makes use of CURLINO_EFFECTIVE_URL. You can look it up on phpdoc here

EDIT:

if you are certain the oldUrl is not redirecting to newUrl via javascript, then you can also avoid fetching the body of the newUrl using

curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body 

Put the above line before $res = curl_exec($ch); in the function getRedirect to achiever faster execution.

like image 194
Prasanth Avatar answered Oct 16 '22 13:10

Prasanth


public function getRedirect($url) {
    $headers = get_headers($url, 1);
    if (array_key_exists("Location", $headers)) {
        $url = getRedirect($headers["Location"]);
    }
    return $url;
}
like image 1
Waleed Khan Avatar answered Oct 16 '22 13:10

Waleed Khan