All posts tagged “PHP”

Shortening URLs in PHP with the API

Simply replace yourusername with your username and yourapikey with your API key which can be found at

function shorten_url($url) {
    if (!$url) { return false; }
    $bitly_username = 'yourusername';
    $bitly_api_key = 'yourapikey';
    $url = urlencode(trim($url));
    $api_address = ''.$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);
    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('');