Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine Final Destination of a Shortened URL in PHP?

How can I do this in PHP? e.g.

bit.ly/f00b4r ==> http://www.google.com/search?q=cute+kittens

In Java, the solution is this:

You should issue a HEAD request to the url using a HttpWebRequest instance. In the returned HttpWebResponse, check the ResponseUri.

Just make sure the AllowAutoRedirect is set to true on the HttpWebRequest instance (it is true by default). (Thx, casperOne)

And the code is

private static string GetRealUrl(string url)
{
    WebRequest request = WebRequest.Create(url);
    request.Method = WebRequestMethods.Http.Head;
    WebResponse response = request.GetResponse();
    return response.ResponseUri.ToString();
}

(Thx, Fredrik Mork)

But I want to do it in PHP. HOWTO? :)

like image 835
Zack Burt Avatar asked Mar 01 '23 09:03

Zack Burt


2 Answers

The time to try, you already found the answer.

Still, I would have gone with something like this :

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://bit.ly/tqdUj");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);

$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

curl_close($ch);

var_dump($url);

Some explanations :

  • the requested URL is the short one
  • you don't want the headers
  • you want to make sure the body is not displayed -- probably useless
  • you do not want the body ; ie, you want a HEAD request, and not GET
  • you want locations to be followed, of course
  • once the request has been executed, you want to get the "real" URL that has been fetched

And, here, you get :

string 'http://wordpress.org/extend/plugins/wp-pubsubhubbub/' (length=52)

(Comes from one of the last tweets I saw that contained a short URL)


This should work with any shortening-URL service, independantly of their specific API.

You might also want to tweak some other options, like timeouts ; see curl_setopt for more informations.

like image 87
Pascal MARTIN Avatar answered Mar 07 '23 06:03

Pascal MARTIN


<?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, 1));
?>
like image 21
Robert French Avatar answered Mar 07 '23 08:03

Robert French