Created
September 12, 2011 15:22
-
-
Save sudar/1211536 to your computer and use it in GitHub Desktop.
Expand Short urls. More details at http://sudarmuthu.com/blog/expand-any-shortened-url-using-php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Expand short urls | |
* | |
* @param <string> $url - Short url | |
* @return <string> - Longer version of the short url | |
*/ | |
function expand_url($url){ | |
//Get response headers | |
$response = get_headers($url, 1); | |
//Get the location property of the response header. If failure, return original url | |
if (array_key_exists('Location', $response)) { | |
$location = $response["Location"]; | |
if (is_array($location)) { | |
// t.co gives Location as an array | |
return expand_url($location[count($location) - 1]); | |
} else { | |
return expand_url($location); | |
} | |
} | |
return $url; | |
} | |
/** | |
* Test Short urls | |
*/ | |
function test_expand_url($short_url, $expected_long_url) { | |
$actual_long_url = expand_url($short_url); | |
if ($actual_long_url == $expected_long_url) { | |
return "Pass for $short_url <br>"; | |
} else { | |
return "Fail for $short_url <br>"; | |
} | |
} | |
// Run testcases | |
echo test_expand_url('http://bit.ly/J8ytTI', 'http://warpspire.com/talks/chooseyouradventure/?utm_source=twitterfeed&utm_medium=twitter'); | |
echo test_expand_url('http://t.co/hyK0qQCR', 'http://warpspire.com/talks/chooseyouradventure/?utm_source=twitterfeed&utm_medium=twitter'); | |
echo test_expand_url('http://sudarmuthu.com', 'http://sudarmuthu.com'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! Is there a cURL version for it?