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? :)
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 :
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.
<?php
$url = 'http://www.example.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With