Relative URLs and HTTPS with CodeIgniter

Warning: this hasn't been thoroughly tested yet.

Define an absolute base URL

config.php

$config['base_url']	= "";
$config['base_url_absolute']	= "http://mydomain.com/toto/";  // used only to trigger HTTPS

Two methods to trigger HTTPS

MY_url_helper.php

if ( ! function_exists('force_ssl'))
{
    function force_ssl()
    {
        if ($_SERVER['SERVER_PORT'] != 443)
        {
			$CI =& get_instance();
			$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url_absolute']);
			redirect($CI->uri->uri_string());
        }
    }
}
 
if ( ! function_exists('remove_ssl'))
{
	function remove_ssl()
	{
	    if ($_SERVER['SERVER_PORT'] != 80)
	    {
			$CI =& get_instance();
			$CI->config->config['base_url'] = $CI->config->config['base_url_absolute'];
			redirect($CI->uri->uri_string());
	    }
	}
}

Inspiration: http://codeigniter.com/forums/viewthread/83154/#454992

hook to switch from and to HTTPS

Comes after the other hook.

// switch from or to https if necessary
$hook['post_controller_constructor'][] = array(
	'class' => '',
	'function' => 'trigger_https',
	'filename' => 'https.php',
	'filepath' => 'hooks'
	);
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
function trigger_https()
{
	// do nothing for these urls
	$exclude_url_list = array();
	$exclude_url_list[] = '/(.*)js$/';
	foreach ($exclude_url_list as $exclude_url) {
		if(preg_match($exclude_url, uri_string()))
		{
			return;
		}
	}
 
	// switch to HTTPS for these urls
	$ssl_url_list = array();
	$ssl_url_list[] = '/(.*)submit_ending_upload\/(.*)$/';
 
	foreach ($ssl_url_list as $ssl_url) {
		if(preg_match($ssl_url, uri_string()))
		{
			force_ssl();
			return;
		}
	}
 
	// still here? switch to HTTP (if necessary)
	remove_ssl();
}
 
/* End of file https.php */
/* Location: ./system/application/hooks/https.php */
 

Feedback