Super simple way to expand bitly urls using PHP

OK. Agree that bit.ly provides an API for expanding URL’s. The main purpose of our simple exercise here is to use  curl functions in PHP to achieve the same. We will write a simple function that will accept a bitly url as parameter. Then we will use curl to get the expanded url.

Below is the full code for function which we will call expandURL.

	function expandURL($url)
	{
		$retVal = 'Error';
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		if(curl_exec($ch) != false)
		{
			$response = curl_exec($ch);
			if($response != false)
			{
				$responseInfo = curl_getinfo($ch);
				if($responseInfo['http_code'] == 200)
				{
					$retVal =  'Expanded URL: '.$responseInfo['url'];
				}
				else if($responseInfo['http_code'] == 404)
				{
					$retVal =  'URL Not found';
				}
				else
				{
					$retVal =  'HTTP error: '.$responseInfo['http_code'];
				}
			}
			else
			{
				$retVal =  curl_error($ch);
			}
		}
		else
		{
			$retVal =  'cURL error ocurred : '.curl_error($ch);
		}
		curl_close($ch);
		return $retVal;
	}
 
	$result = expandURL('http://bit.ly/LoDhO');
	echo $result;

How this works?

$retVal is the return value from function. First we initialize a curl session for bitly url using curl_init. Next 2 lines are most important.

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

Since our aim is not to display any output directly in browser, we will set CURLOPT_RETURNTRANSFER to 1 (true). It will  return the value after curl execution in a string and will not output anything to browser.

Another point worth noting is setting CURLOPT_FOLLOWLOCATION to true. We can safely assume that bit.ly redirects the short URL to its original location. Setting CURLOPT_FOLLOWLOCATION to true will allow curl to follow any HTTP redirects that are done by bitly. This is the only way we can reach the final URL.

Next we exceute curl using curl_exec. By default it returns true or false. Since we have set CURLOPT_RETURNTRANSFER  to true, it will return a string as response.

After successful execution of curl, we can get information about it using curl_getinfo. curl_getinfo returns an associative array which contains several values including the final url, http code, transfer time etc (try printing it using print_r).

Finally, all we have to do is check if the response http code from curl_getinfo is 200 (OK). If it is, we extract the URL from the array otherwise we check if it is error 404 (not found) or any other http error and return appropriate value.

Related Posts

php

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

3 Responses to “Super simple way to expand bitly urls using PHP”

Leave Comment

(required)

(required)


10,926 spam comments
blocked by
Akismet