Using CakePHP 1.3 we have a booking system for hotel rooms. A check-availability form should bring the user to a secure payment page (https://secure.domain.com/bookings/payment)
I used the example from http://techno-geeks.org/2009/03/using-the-security-component-in-cakephp-for-ssl/ but found it problematic. I ended up adding the following to my app_controller.php.
The code below redirects HTTPS to www.example.com and HTTP to example.com. If a user is logged in (see $loggedUser
), it forces HTTPS for every connection.
// Pages requiring a secure connection.
$secureItems = array();
// beforeFilter
function beforeFilter() {
// Your logic...
$this->__checkSSL();
}
/**
* Check SSL connection.
*/
function __checkSSL() {
/** Make sure we are secure when we need to be! **/
if (empty($this->loggedUser)) {
if (in_array($this->action, $this->secureItems) && !env('HTTPS')) {
$this->__forceSSL();
}
if (!in_array($this->action, $this->secureItems) && env('HTTPS')) {
$this->__unforceSSL();
}
} else {
// Always force HTTPS if user is logged in.
if (!env('HTTPS')) {
$this->__forceSSL();
}
}
}
/**
* Redirect to a secure connection
* @return unknown_type
*/
function __forceSSL() {
if (strstr(env('SERVER_NAME'), 'www.')) {
$this->redirect('https://' . env('SERVER_NAME') . $this->here);
} else {
$this->redirect('https://www.' . env('SERVER_NAME') . $this->here);
}
}
/**
* Redirect to an unsecure connection
* @return unknown_type
*/
function __unforceSSL() {
if (strstr(env('SERVER_NAME'), 'www.')) {
$server = substr(env('SERVER_NAME'), 4);
$this->redirect('http://' . $server . $this->here);
} else {
$this->redirect('http://' . env('SERVER_NAME') . $this->here);
}
}