Sponsor
Now Playing
- Alix Perez – I'm Free 3 hours ago
- Alix Perez – Intersections 3 hours ago
- Alix Perez – Forsaken 3 hours ago
- Glen E Ston – Ouroboros (Original Mix) 3 hours ago
- Black Sun Empire – Everything 3 hours ago
CakePHP URL Shortener Service Tutorial
August 26, 2009,
3,871 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
10 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
5 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 [...]