Deluxe Blog Tips About Projects

Easily Expand Short URL Using PHP

Expand Short URL Using PHP

Short url services like bit.ly, tinyurl are very helpful to make a short version of our long urls. In some cases, we want to expand short url to make sure it has been shortened correctly, or to check if someone gives us a harmful link. Expanding short url to long url using PHP is easy as we’ll see in this article.

The key idea of expanding method is checking HTTP headers. We know that every short url services uses a redirection instruction to tell the browser to redirect to the right long url. So, in our PHP script, we just have to check the new location and return it.

The code is simple as the following:

function expandShortUrl($url) {
    $headers = get_headers($url, 1);

    return $headers['Location'];
}

// will echo https://deluxeblogtips.com
echo expandShortUrl('http://tinyurl.com/27lmz7j');

To get HTTP headers, we use get_headers function. This function has 2 parameters: first is the url, second is the format of returned array, if it’s set to 1, get_headers() parses the response and sets the array’s keys.

If we echo raw value of $headers, using print_r($headers), we get:

Array (
    [0] => HTTP/1.0 301 Moved Permanently
    [X-Powered-By] => PHP/5.2.12
    [Location] => https://deluxeblogtips.com
    [Content-type] => text/html
    [Content-Length] => 0
    [Connection] => close
    [Date] => Array (
        [0] => Sat, 01 May 2010 18:14:56 GMT
        [1] => Sat, 01 May 2010 18:14:55 GMT
    )
    [Server] => Array (
        [0] => TinyURL/1.6
        [1] => GSE
    )
    [1] => HTTP/1.0 200 OK
    [X-Frame-Options] => ALLOWALL
    [Content-Type] => text/html; charset=UTF-8
    [Expires] => Sat, 01 May 2010 18:14:55 GMT
    [Last-Modified] => Sat, 01 May 2010 17:00:19 GMT
    [ETag] => "dd6d44c4-46c9-44bb-aec2-17946eb627a1"
    [X-Content-Type-Options] => nosniff
    [X-XSS-Protection] => 0
    [Cache-Control] => public, max-age=0, must-revalidate, proxy-revalidate
    [Age] => 0
)

All we need is the Location value only, so we return $headers['Location'].

The expandShortUrl function is simple and requires PHP5 to make et_headers works. It’s OK because most web servers now are using PHP5. The function works with all short url services: bit.ly, tinyurl, is.gd, google shortener, etc.

Subscribe to the Newsletter

Subscribe to get my latest content by email. I won't send you spam. Unsubscribe at any time.