My Ride
Started: Friday 24th May 2013 4:33pm
Distance: 17.46km
Duration: 00:39:15
Rest Time: 00:06:05
Climb: 124m
Max Speed: 51.48kmph
Average Speed: 26.68kmphInstagrams
-
Recent Posts
Recent Comments
- Arie on Tag Time: CakePHP Tag Plugin
- Paul on Sign Me Up A CakePHP User Registration Plugin
- Paul on Sign Me Up A CakePHP User Registration Plugin
- Watch The Big Bang Theory season 6 episode 13 on On My Tv: With Trakt.tv
- veloura et bellagenix on Ultimate Guestbook Tutorial: How to build a Guestbook with a honeypot, error checking, IP banning, pagination, e-mail notification and smilies with PHP and mySQL
Archives
- February 2013
- December 2012
- September 2012
- July 2012
- January 2012
- September 2011
- August 2011
- February 2011
- January 2011
- November 2010
- October 2010
- August 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
Categories
Meta
CakePHP URL Shortener Service Tutorial
August 26, 2009,
19,026 views
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






14 Comments
i have never seen such a comprehensive tutortial on this , good on yah, i’ll buy you a paypal beer any day
great work, thank you!
Awesome tutorial man! Thanks allot
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.
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.
The demo file not work http://jotlab.com/tutorials/url/, url not found
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;
}
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!
>>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!
No problem at all! Thanks for your input
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?
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
@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.
Hi there, I read your blog on a regular basis. Your humoristic style is witty,
keep up the good work!
8 Trackbacks
[...] CakePHP URL Shortener Service Tutorial • Jotlab [...]
[...] Jotlab has a post on going from clean install to working URL shortener in 8 simple pages. [...]
[...] CakePHP URL Shortener Service Tutorial [...]
[...] CakePHP URL Shortener Service Tutorial [...]
[...] 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 [...]
[...] 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, [...]
[...] View The Tutorial : CakePHP URL Shortener Service Tutorial [...]
[...] Cómo hacer un acortador de URL’s con CakePHP. [...]