URL Redirectors

Derek Jones edited this page Jul 5, 2012 · 9 revisions
Clone this wiki locally

Category:Contributions::Applications

I have created a URL Redirecting service using CodeIgniter 1.7.1. If you are interested in the source, let me know and I will post the controllers and models.

The site is called 9source. The URL is http://9src.com

It was actually very easy to create. The hardest part was generating the short URL. I had to come up with a way to create a unique identifier, and keep it short. I came up with the idea of just starting the first one at 'a' (url of http://9src.com/a) and then "add" 1 to it each time. URLs would end up looking like this:

-http://9src.com/a -http://9src.com/b -http://9src.com/c -http://9src.com/d ... -http://9src.com/z -http://9src.com/A -http://9src.com/B -http://9src.com/C ... -http://9src.com/Z -http://9src.com/aa -http://9src.com/ab -http://9src.com/ac and so on...

Here is the code that makes this happen:


    function increase_string($str)
    {
        $len = strlen($str);
        $inced = false;
        
        for($i = $len - 1; $i >= 0; $i--)
        {
            if($str[$i] != 'Z')
            {
                $str[$i] = $this->increase_letter($str[$i]);
                break;
            }
            else
            {
                $str[$i] = "a";
                if($i == 0)
                {
                    $str = "a" . $str;
                }
            }
        }
        return $str;
    
    }
    function increase_letter($letter)
    {
        //Lowercase: 97-122
        //Uppercase: 65-90
        $ord = ord($letter);
        if($ord == 122)
        {
            $ord = 65;
        }
        else
        {
            $ord++;
        }
        return chr($ord);
    }

To use it you simply call it like this:

$this->increase_string("a");

It will return "b". Likewise, if you send it "snfiz", it will return "snfiA".

You may be saying to yourself "Why not just use the 'id' column from the database?" Consider this:

Say I have 2,785,243 (random number) URLs in the database. That would make the "short" url look like this: http://9src.com/2785243. However, using my method, the URL looks like this: http://9src.com/sPbs. 3 characters shorter may not seem like much, but the whole point of the site is to create SHORT urls.