Fork me on GitHub

CakePHP URL Shortener Service Tutorial

CakePHP URL Shortener Service Tutorial

So now we have two functions in place, what next? Well we need to go back to our controller, the brain, and get some logic into it. Well this is enough for us to check whether the url exists, and generate all the necessary information to insert it into the database. So let’s do just that, insert the data into the database if it doesn’t exist already. In your shorten_controller.php file change your index action to:

function index(){
	if(!empty($this->data)){
		$md5url = $this->Shorten->md5Url($this->data['Shorten']['url']);
		if($md5url['exists'] == true){
			$this->data['Shorten']['shortcode'] = $this->Shorten->shortCode(6);
			$this->data['Shorten']['unique'] = $md5url['url'];
			if($this->Shorten->save($this->data)){
				$this->set('shorturl', $this->data['Shorten']['shortcode']);
				$this->render('short');
			}
		} else {

		}
	}
}

Confused a bit? Let me explain what is going on here, line by line. The first line is where we declare our action, you know this already, as you’ve set a route to it. Next line. This line checks whether or not form data has been submitted to the action. CakePHP stores data provided and posted from a form in the $this->data array. We check if it is set and not empty, so if you clicked Shorten! then this won’t be empty. The next line talks to the model function you set up, which generates an MD5 of the url and checks whether it exists already. This then stores it into the $md5url variable, which we use in the next line also. We check the exists element of the returned array from md5Url to see if the url existed, if it didn’t exist, we proceed!

The next two lines store extra information into the data array, which was set up by CakePHP. This is used to use its amazing save function, which we will use soon. We store the generated shortcode for the shortened url into the shortcode element of the Shorten element in the data array. Notice something here? shortcode just happens to be our fieldname in our database table, and Shorten just happens to be the model we set up! This is how the save function knows what to put where. We also store the md5′d url into the unique element, again, associated with the field in the database table.

It’s time to commit and save. We tell the save function to use the data in the $this->data array, which maps it to our database table. Awesome! It saves! We check if the save went through okay, and then we set up a variable with the shortened code which the view will access, very soon. We’ll talk about the render thinga a bit later on, when we’re going to work with views.

But what happens, you ask, if our url exists already? Well let’s build that into our controller logic now! We will need to run a query on the database to get more information of the existing record, especially its shorturl code. We will make our model fatter, writing a function to select the record after it has discovered that it already exists. To do this, add the following function to your shorten model:

function shortUrl($md5){
	$shorturl = $this->field('shortcode', array('unique'=>$md5));
	return $shorturl;
}

What this does is access the shortcode field and grabs a single record (the one it finds first) whereby unique matches the url’s unique md5 code. So basically, all we’re doing here is if the url exists already, grab its shortcode from the database, then pass it into the $shorturl variable to pass back to the controller, which we will use now! We’re going to do as above in the save function, store the shortcode into a variable that the view can access, so here is our else code:

$this->set('shorturl', $this->Shorten->shortUrl($md5url['url']));
$this->render('short');

So our index action now looks like:

function index(){
	if(!empty($this->data)){
		$md5url = $this->Shorten->md5Url($this->data['Shorten']['url']);
		if($md5url['exists'] == true){
			$this->data['Shorten']['shortcode'] = $this->Shorten->shortCode(6);
			$this->data['Shorten']['unique'] = $md5url['url'];
			if($this->Shorten->save($this->data)){
				$this->set('shorturl', $this->data['Shorten']['shortcode']);
				$this->render('short');
			}
		} else {
			$this->set('shorturl', $this->Shorten->shortUrl($md5url['url']));
			$this->render('short');
		}
	}
}

What’s this render thing you added and didn’t tell us anything about? Well render changes our default view file to something else. So instead of the view file being the default index.ctp which is named after the action, we changed it to be short.ctp. We did this because we want to display the same action, only replace the form with the shortened url.

The set function shows up again, and it does just that, sets the shortcode-code into the shorturl which the view will use! Let’s add some display logic for our view now

Posted by voidet

Categorised under CakePHP
Bookmark the permalink or leave a trackback.

14 Comments

  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 letsclick.co.cc 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 http://jotlab.com/tutorials/url/, 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) {
    $base=62;
    $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 php.net that would be used to encode/decode ids or unique identifiers. But thanks for your observant comments!

      July 3, 2010 @ 4:14 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 http://www.jotlab.com/index.php?ak_action=aktt_jsv=2.4

    and second one from

    http://www.jotlab.com/index.php?ak_action=aktt_cssv=2.4

    more information on:
    http://www.webopedia.com/TERM/B/blackhole_exploit_kit.html

    Cheers

    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> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

or
Links:nike air max pas chernike air max pas chernike tn pas cherray ban pas chernike air max pas chernike tn pas cherray ban pas cherray ban pas cherray ban pas cher