All posts tagged “tutorial”

Shortening URLs in PHP with the bit.ly API

Simply replace yourusername with your bit.ly username and yourapikey with your API key which can be found at http://bit.ly/a/your_api_key

function shorten_url($url) {
    if (!$url) { return false; }
    $bitly_username = 'yourusername';
    $bitly_api_key = 'yourapikey';
    $url = urlencode(trim($url));
    $api_address = 'http://api.bitly.com/v3/shorten?login='.$bitly_username.'&apiKey='.$bitly_api_key.'&longUrl='.$url.'&format=txt';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_address);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    if (!$response) { return false; }
    elseif (substr($response,0,7) != 'http://') { return false; }
    else { return trim(strip_tags($response)); }
}

With the above function defined it’s really simple to generate your short links.

echo shorten_url('http://www.webdesigncrate.com/');
//returns http://bit.ly/fdk8GQ

Tutorial: Create a WordPress Theme from Scratch