CakePHP URL Shortener Service Tutorial

CakePHP URL Shortener Service Tutorial

Now that we have our basic layout looking awesome, let’s go ahead and start building our site up to accept urls to smash and shorten! Within the app directory and go into the controller folder. Controllers are the logic, the brains and the masterminds behind the site operations. Once an action is requested the controller jumps into action, pulling data from the database, sending it to the views and then to the browser. Think of the controller as a middleman, a middleman with a heap of power! We’ll create a blank middleman, or task for our middleman, called an action. Create a blank file within the controllers folder and call it shorten_controller.php. Next dump this basic code into it:

	class ShortenController extends AppController {
		function index(){

This is the barebones of a controller with an action. Firstly we have extended the base class of a controller object of which the geniuses behind CakePHP have created for us. Then we setup a function, called index, which just so happens to be our action! We will build upon this action now, to be our index page, of which will accept a url from a user, validate it, then crunch it, store it in the database and then redirect to another page/action to display the lucky user’s new shortened url.

Let’s get rid of this pesky CakePHP code shall we? In order to do this, we need to tell CakePHP that we have a new default action that we’d like to use for our index/default page. To do this, we’re going to have to route, and route all night long. Open up the routes.php file within the config folder. You will notice this line:

Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));

Awesome. We need to change this to connect our default or ‘/’ root url to the root action we created, which was Shorten::index. To do that, change the previous line to:

Router::connect('/', array('controller' => 'shorten', 'action' => 'index'));

Now check your page again! It should come out a little different. We still get a complaint, but we’re going to handle that now!


Let’s take care of this missing table error message now and sort our database out to start accepting and storing urls!

Posted by voidet

Categorised under CakePHP
Bookmark the permalink or leave a trackback.


  1. i have never seen such a comprehensive tutortial on this , good on yah, i’ll buy you a paypal beer any day 🙂

    August 26, 2009 @ 3:07 pm
  2. hendrik

    great work, thank you!

    August 31, 2009 @ 5:39 am
  3. Awesome tutorial man! Thanks allot

    December 16, 2009 @ 4:25 am
  4. nice post..what about stat a.k.a link tracking? it will be great if u include it.
    i bake mine at for learning purpose.

    April 30, 2010 @ 7:43 am
    • VoiDeT

      That would be quite easy, just depends how much information you would like to store.
      For example you could simply increment a count field in the row for that entry.
      Or you could make a completely new table in the database that would log each view/click and the according information, like IP, datetime etc.

      April 30, 2010 @ 9:00 am
  5. The demo file not work, url not found

    May 23, 2010 @ 3:30 am
  6. Hi, i don like very much the function getFilename. Why dont you try using a function the transform the id of the link into a string with numbers and letters?

    pseudocode for add a link;
    // find link, if not in database insert new link
    // link_shorted= base_convert($link_id, 10, 36);
    // return link_shorted

    pseudocode for get a encoded link;
    // link_id= base_convert($link_code, 36,10);
    // search link by id
    // redirect

    if you want even shorter link you could use this functions;

    function any2dec( $num) {
    $index = substr( “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”, 0, $base );

    $out = 0;
    $len = strlen( $num ) – 1;
    for ( $t = 0; $t = 0; $t– ) {
    $a = floor( $num / pow( $base, $t ) );
    $out = $out . substr( $index, $a, 1 );
    $num = $num – ( $a * pow( $base, $t ) );
    return $out;

    July 3, 2010 @ 4:11 pm
    • VoiDeT

      Exactly right. This is why at the beginning I said it wasn’t the best way to do it. But for the sake of this intermediate tutorial i thought using those baseencodes would be far beyond the scope of the tutorial. I did find similar functions on that would be used to encode/decode ids or unique identifiers. But thanks for your observant comments!

      July 3, 2010 @ 4:14 pm
      • If I load the website in chrome it doesn’t show all images,also when I click on those images they redirect me somewhere else please can you check it.

        And is there any option to post a file with code inside of it that is perfect.

        November 26, 2015 @ 10:37 pm
  7. >>Exactly right. This is why at the beginning I said it wasn’t the best way to do it.

    upss, i didnt read anything i just read the code, my bad!

    July 3, 2010 @ 4:19 pm
    • VoiDeT

      No problem at all! Thanks for your input 🙂

      July 3, 2010 @ 4:21 pm
  8. Hi all!

    Thanks for that great tutorials. the thing that make me a bit uncomfortable is what will the effect of making url shortened on the site in the term of speed. and talking about dynamic links how will you get shortcode will model association useful in that case. one more question in the routes.php you have write

    Router::connect(‘/:shortcode’, array(‘controller’ => ‘shorten’, ‘action’ => ‘redirectUrl’), array(‘pass’=>array(‘shortcode’)));

    it will redirect whenever you write anything after ‘/’ for rss feed and xml link will it don’t cause problem?

    March 21, 2011 @ 10:02 pm
  9. Hey man … everytime when i am going to open your page my virus protection pops up and displays an exploit : Blackhole Exploit Kit (type 2170) which comes from

    and second one from

    more information on:


    June 5, 2012 @ 6:27 pm
  10. VoiDeT

    @kapil – Sorry the first part I do not understand your english. The second question is true. It will capture all urls with /url. But if you don’t want that, put your urls above that and use shortcode as the last catchall.

    June 5, 2012 @ 7:03 pm
  11. Hi there, I read your blog on a regular basis. Your humoristic style is witty,
    keep up the good work!

    January 4, 2013 @ 12:54 am

8 Trackbacks

  1. […] CakePHP URL Shortener Service Tutorial • Jotlab […]

  2. […] Jotlab has a post on going from clean install to working URL shortener in 8 simple pages. […]

  3. […] CakePHP URL Short­ener Ser­vice Tutorial […]

  4. By 9 Awesome CakePHP Tutorials | DevMoose on June 27, 2010 at 12:02 am

    […] CakePHP URL Shortener Service Tutorial […]

  5. […] 2010 por eugenio85 Etiquetado: acortador, cakephp, PHP, tutorial, url shortener Despues de leer este articulo decidi escribir mi propio tutorial, mientras pensaba en como escribir note que en meneame utilizan […]

  6. […] sidebar */ google_ad_slot = "1113860990"; google_ad_width = 300; google_ad_height = 250; 1. CakePHP URL Shortener Service Tutorial by JotLabIn this tutorial I will be creating this website using CakePHP 1.2.4, because it rocks, […]

  7. […] View The Tutorial :  CakePHP URL Shortener Service Tutorial […]

  8. By Frameworks: muchos recursos para comenzar con CakePHP on December 28, 2012 at 7:07 am

    […] Cómo hacer un acortador de URL’s con CakePHP. […]

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">