Using Bitly API to shorten URLs

John picture John · Apr 27, 2011 · Viewed 7.2k times · Source

I found the Bitly API code below on this site. I'm having a hard time getting it to create and then echo a Bitly shortened URL for a variable called $fullurl. How would I do that?

EDIT: No error code appears, just no bitly shortened URL is shown.

EDIT 2: var_dump($response); returns NULL

EDIT 3: I did replace the API login and key with my mine.

EDIT 4: I found the answer in one of the comments on the original tutorial. My question was too basic for all you PHP pros: I simply needed to add echo bitly_shorten($fullurl); at the end.

Thanks in advance,

John

function bitly_shorten($url)
{
    $query = array(
        "version" => "2.0.1",
        "longUrl" => $url,
        "login" => API_LOGIN, // replace with your login
        "apiKey" => API_KEY // replace with your api key
    );

    $query = http_build_query($query);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://api.bit.ly/shorten?".$query);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec($ch);
    curl_close($ch);

    $response = json_decode($response);

    if($response->errorCode == 0 && $response->statusCode == "OK") {
        return $response->results->{$url}->shortUrl;
    } else {
        return null;
    }
}

Answer

Bob Jeey picture Bob Jeey · May 17, 2012

Change it to:

function bitly_shorten($url){
  $query = array(
    "version" => "2.0.1",
    "longUrl" => $url,
    "login" => API_LOGIN, // replace with your login
    "apiKey" => API_KEY // replace with your api key
  );

  $query = http_build_query($query);

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "http://api.bitly.com/v3/shorten?".$query);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  $response = curl_exec($ch);
  curl_close($ch);

  $response = json_decode($response);
  if( $response->status_txt == "OK") {        
    return $response->data->url;
  } else {
    return null;
  }
}