~ Working with SSL in Codeigniter ~
Wednesday, March 11th, 2009
For the best part of 3 months I’ve been trying to find an elegant way to switch between http:// and https:// for certain pages. I crawled the forums and found a number of solutions. The first was to use the .htaccess file and mod_rewrite to rewrite the url. This solution was fine on one server but I had to switch recently and suddenly it was failing miserably for no reason that I could determine, so I was forced to find another way. As always, finding another way is a _good_ thing, and the way I found is nicer, easier and much more dynamic.
Create a file in application/helper called ssl_helper.php
if (!function_exists('force_ssl'))
{
function force_ssl()
{
$CI =& get_instance();
$CI->config->config['base_url'] =
str_replace('http://', 'https://',
$CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 443)
{
redirect($CI->uri->uri_string());
}
}
}
function remove_ssl()
{
$CI =& get_instance();
$CI->config->config['base_url'] =
str_replace('https://', 'http://',
$CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 80)
{
redirect($CI->uri->uri_string());
}
}
Load the helper, then in the constructor for any controller that requires ssl, simply insert:
force_ssl();
In every controller that you don’t want to have ssl put:
if (function_exists('force_ssl')) remove_ssl();
And there you go. I found the force_ssl function on the Codeigniter forum, so all credit goes to the original poster. All I did was provide a function to switch back.
3 Responses
June 9th, 2009 at 12:35 pm
This is a great solution. It works perfectly. I hope they build something similar into future releases of Codeigniter as standard.
June 18th, 2009 at 12:01 pm
Finally my search towards the pure dynamic Working with SSL in Codeigniter got the right path .you are the one that have the great solutions. Hope to get on future……………
May 14th, 2010 at 10:08 pm
Great solution and way easier than the .htaccess mess. Thanks!