Super simple way to expand bitly urls using PHP

OK. Agree that 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.

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.

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 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

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

  1. i am getting this error
    Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in /home/ramakris/public_html/curl.php on line 11
    HTTP error: 301. What to do?

  2. According to PHP manual:
    “Disabled CURLOPT_FOLLOWLOCATION in curl when open_basedir or safe_mode are enabled.”

    Did you check open_basedir and safe_mode settings in php.ini. safe_mode and open_basedir must be disabled for this to function.

    Also, please note that these features has been deprecated from PHP 5.3 and will be removed from PHP 6

Leave a Reply