Flic.kr Short URL Encode/Decode Demo 2/4/11

Flickr creates a custom short url for each of your images, but unfortunately it isn't available via the api. However, if you know the ID of the photo, this PHP function will let you generate the short url. There's a decode function here as well that helps you construct the full url from the shortened one (though you need to know the username to construct the full url).

Note: Most of the code here has been adapted from this discussion.

Demo

Hiccup.

Code

Here are the two functions at work in the demo above.

The first function creates the short url when passed the full photo url. The second function will decode the full photo url from the short url.

Note: You need to know the username to construct the full url from the short one. I've set the username in a variable at the beginning.


<?php
// Change this...
$user_name = "plasticmind"; // for constructing full URLs

// ...but not this!
$alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; // Flic.kr uses base58 to encode 

function flickrShorten($longurl) {
    global $alphabet;
    $longurl_boom = explode("/", $longurl);
    $longid = $longurl_boom[5]; // Harvest the photo id (long) from the url
    $base_count = strlen($alphabet);
    $encoded = '';
    while ($longid >= $base_count) {
        $div = $longid/$base_count;
        $mod = ($longid-($base_count*intval($div)));
        $encoded = $alphabet[$mod] . $encoded;
        $longid = intval($div);
    }
    if ($longid) $shortid = $alphabet[$longid] . $encoded;
    if($shortid>0) {
        $shorturl = "http://flic.kr/p/" . $shortid;
        return $shorturl;        
    }
}

function flickrUnshorten($shorturl) {   
    global $alphabet, $user_name;
    $shorturl_boom = explode("/", $shorturl);
    $shortid = $shorturl_boom[4]; // Harvest the photo id (short) from the url
    $decoded = 0;
    $multi = 1;
    while (strlen($shortid) > 0) {
        $digit = $shortid[strlen($shortid)-1];
        $longid += $multi * strpos($alphabet, $digit);
        $multi = $multi * strlen($alphabet);
        $shortid = substr($shortid, 0, -1);
    }
    if($longid>0) {
        $longurl = "http://flickr.com/photos/" . $user_name . "/" . $longid;
        return $longurl;        
    }
}
?>
            

Calling to the functions is simple. Pass in the long url and you'll get the short one back.


<?php
    $encoded_short_url = flickrShorten('http://flickr.com/photos/plasticmind/2453367893');
    echo "<a href='$encoded_short_url'>$encoded_short_url</a>";
?>
    

Pass in the short url and you'll get the long one back. (Be sure you've set the username.)


<?php
    $decoded_long_url = flickrUnshorten('http://flic.kr/p/8ufih2');
    echo "<a href='$decoded_long_url'>$decoded_long_url</a>";        
?>
        

Feedback goes here // by Plasticmind