Tanveer’s Weblog

CakePHP: Creating a route usage https (SSL connection)

July 9, 2008 · 8 Comments

While playing in my workspace i need to make a route which should be use a secure path. That means https (SSL connection). So after googled for while i got the idea. Basically what i need is.. when an user in my sing in page will go through via the ssl connection. After entering user name and password will validated and redirect in to another location. So usually user will go through in https protocol then again redirected into http.

Here what i did;

Well, obviously i use cake’s component

1. Create a file ssl.php into app/controllers/components/
paste this code

<?php
class SslComponent extends Object {

var $components = array('RequestHandler');

var $Controller = null;

function initialize(&$Controller) {
$this->Controller = $Controller;
}

function force() {
if(!$this->RequestHandler->isSSL()) {
$this->Controller->redirect('https://'.$this->__url());
}
}

function unforce() {
if($this->RequestHandler->isSSL()) {
$this->Controller->redirect('http://'.$this->__urll());
}
}

function __url() {
$port = env('SERVER_PORT') == 80 ? '' : ':'.env('SERVER_PORT');

return env('SERVER_NAME').$port.env('REQUEST_URI');
}

function __urll() {
$port = env('SERVER_PORT') == 443 ? '' : ':'.env('SERVER_PORT');

return env('SERVER_NAME').$port.env('REQUEST_URI');
}

}
?>

you can find it also here but i added unforce() and __urll() ;)

3. Now, in my case only when user click in to sign in or lend now, I need the https connection. Thats why, in my home controller i added this beforeRender() method, but make sure you assign this Ssl component.

var $components = array( 'Ssl' );
public function beforeRender(){

$action = array( 'signin', 'lendnow' );

if( in_array( $this->params['action'] , $action ) ){

     $this->Ssl->force();
}else{
     $this->Ssl->unforce();
}

}

So, i will create a secure connection with my apache server.
4. User now enter their user name and password and submit

5. If anyone click beside this they will have only http connection

That’s it

enjoy ;)

Categories: Tips' n Tricks' · cakePHP
Tagged:

8 responses so far ↓

Leave a Comment