My Ride
Started: Wednesday 19th June 2013 4:52pm
Distance: 25.47km
Duration: 00:53:28
Rest Time: 00:03:38
Climb: 219m
Max Speed: 57.96kmph
Average Speed: 28.58kmphInstagrams
-
Recent Posts
Recent Comments
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,312 views
Now we’re about to get our database table set up. But before I show you the SQL code to run against your database, let me first explain how the logic of the site is going to play out:
- First a user arrives on our awesome webpage
- They next enter a website url into the url input field, they submit the form
- Our system first checks if the url exists within the system
- If the url exists, then the already shortened code is displayed back to the user on the following page
- If the url doesn’t exist, then a random set of 6 characters is generated to be its shortened url code. Also something else happens, the original url is stored, so as to redirect to the correct page, but the url is also md5 encoded, to represent a unique identifier for that url. We’ve indexed this unique identifier column, to reduce the stress on our cringing database.
- The user gets redirected to the url if the shortened code is navigated to.
So what does this mean? Well, we need some columns! A place to store the real URL, a md5 of the url and a randomly generated unique string for the url. Below is the SQL we’ll be using to get our url table sorted:
CREATE TABLE IF NOT EXISTS `urls` ( `id` int(11) unsigned NOT NULL auto_increment, `url` text NOT NULL, `shortcode` varchar(16) NOT NULL, `unique` varchar(32) NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`), KEY `unique` (`unique`) );
Get this table sorted, either use the mysql shell or phpmyadmin. Why are we md5-ing the url you might be wondering? Well we don’t want to insert the same url more than once, why should we? It’s the same url, it’d just be taking up a unique code and space on the poor database servers hard drive. We md5 to the url to create a unique reference to the url, because searching through on the field of type text on what could easily be a massive database is very costly to performance! So why don’t I just make the field a varchar of 255? as you might normally. Well URL’s can be quite big, in-fact apache and alot of browsers will go up to a URL length of 4000 characters. Using a varchar field of 4000 is extremely inefficient!
Anyhow, now I hope you understand what’s going on behind the scenes here, let’s get going with making things happen! With the database table set up, go back and refresh your page. Didn’t change anything right? That’s because we did a naughty, and we didn’t follow the conventions of CakePHP! Rebels! The convention should of been to have a table set up called shortens. Or a table called urls and a controller called url_controller.php. Because I like neither of these options, i’ve decided to go rebel.
But it’s all good, we just need to create a model, and to tell it to use the urls table! Models are used for representing table associations, data validation and data handling logic. They are the data droid files if you will. In fact a website and its operations can be regarded as so data centric, that is it probably best to develop functions within the models and called within the controllers, as a way to modularise and reuse code! So this is where fat-assed models and skinny-weeny controllers comes into play.
Let’s make a fat-assed model now. Create a file within the models directory called shorten.php and let’s tell the model which table in the database we wish to associate it with. The key to it is on line 5:
<?php
class Shorten extends AppModel {
var $name = 'Shorten';
var $useTable = 'urls';
}
?>
Awesome! Go and refresh the page again. Argh! Another error! All good! We’re still setting up! This time its telling us that we don’t have a view set up for this action. Which is true, we don’t but as soon as we do, you won’t be seeing anymore errors, only what your final front page should look like. Promised. Before we flip the page, notice anything different in the debugging? You see it’s communicating with our database:







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. [...]