Component for forcing a secure connection
With this simple component you can force the user to use a secure connection to the server.
Usage
To force a SSL connection for a all the action for a single controller just add the force() call in your beforeFilter().
Controller Class:
Download code
<?php
class MyController extends AppController {
var $name = 'My';
var $components = array('Ssl');
function beforeFilter() {
parent::beforeFilter();
//Force a secure connection
$this->Ssl->force();
}
function index() {
}
function view($id) {
}
}
?>
If you want to only force a secure connection for one or two actions you can add the force() call to your actions.
Controller Class:
Download code
<?php
class MyController extends AppController {
var $name = 'My';
var $components = array('Ssl');
//This action will use a forced secure connection
function index() {
$this->Ssl->force();
}
function view($id) {
}
}
?>
You can also force a secure connection for your entire application. Just add the call in your app controller.
Controller Class:
Download code
<?php
class AppController extends Controller {
var $components = array('Ssl');
function beforeFilter() {
$this->Ssl->force();
}
}
?>
The component
Save this code into /app/controllers/components/ssl.php
Component Class:
Download 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 __url() {
$port = env('SERVER_PORT') == 80 ? '' : ':'.env('SERVER_PORT');
return env('SERVER_NAME').$port.env('REQUEST_URI');
}
}
?>
Comments
Comment
1 Does not work if you are using captcha