Get the Original URL behind a Shortened link using PHP

I know a lot of us and our dogs know what shortened links are. If you don’t know – they are long URLs which get shortened for convenient link sharing.
Example of link-shortening service includes bit.ly, su.pr, tiny.cc, goo.gl etc.

In this article, I’m going to show us how to programmatically retrieve the original long URL that got shortened via PHP.
Let’s examine the headers sent by the server in response to the HTTP request sent by http://goo.gl/V0q4SK that redirects to https://w3guy.com using an HTTP Header checker tool.

HTTP Request Header of a shortened link

From the image above, the Location field contains the real URL.

Don’t want to rely on a third-party tool in checking the HTTP header of a URL, use the code snippet below where $url is the variable of the URL to be checked.


print_r(get_headers($url));
Get the original URL of a shortened link

To retrieve the original URL of a shortened link, use the function below.


function get_shorten_url( $url ) {
	$headers = get_headers( $url, 1 );
	$url = $headers['Location'];
	echo $url;
}

Use this function as follows.


get_shorten_url( 'http://goo.gl/V0q4SK' );
Caveat

When a shortened link get shortened again, by passing integer 1 as the second argument to get_headers() returns both the shortened link (that got re-shortened) and the original URL.

A scenario where a shorted link gets re-shorted is when you tweet a shortened link. And you know twitter encode all tweeted link using http://t.co.

In order for our function not to throw an error message when such scenario occurs, here is our re-written function.


function get_shorten_url($url) {
	$headers = get_headers($url, 1);
	$url = $headers['Location'];
	if (is_array($url)) {
		foreach ($url as $url) {
			echo $url . "\n";
		}
	} else {
		echo $url;
	}
}

When I tweeted http://goo.gl/V0q4SK link, the twitter shortened link was http://t.co/TDvHL2dPXf

Using our modified function, we can retrieve the shortened link (that got re-shortened) and the original URL.


get_shorten_url( 'http://t.co/TDvHL2dPXf' );

// Output/result

// http://goo.gl/V0q4SK
// https://w3guy.com/
Don’t miss out!
Subscribe to My Newsletter
Invalid email address