Press ESC to close

Manoj Bist

Force SSL Codeigniter 3

Force SSL In Codeigniter

CodeIgniter is an Application Development Framework – a toolkit – for people who build web sites using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.

Force SSL in Codeigniter, using hooks but you can also force SSL in Codeigniter with htaccess rewrite rules.
Here today i am going to share how you can force SSL in Codeigniter Using Hooks.
What are Hooks?
CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files. When CodeIgniter runs it follows a specific execution process, diagramed in the Application Flow page. There may be instances, however, where you’d like to cause some action to take place at a particular stage in the execution process. For example, you might want to run a script right before your controllers get loaded, or right after, or you might want to trigger one of your own scripts in some other location.
Enabling Hooks
The hooks feature can be globally enabled/disabled by setting the following item in the application/config/config.php file:
$config['enable_hooks'] = TRUE;
Defining a Hook
Hooks are defined in the application/config/hooks.php file. Each hook is specified as an array with this prototype:
$hook['post_controller_constructor'][] = array(
'function' => 'redirect_ssl',
'filename' => 'ssl.php',
'filepath' => 'hooks');
Next, create a new file in application/hooks/ssl.php
Append this code in the file and save.
<?php
function redirect_ssl() {
$CI =& get_instance();
$class = $CI->router->fetch_class();
$exclude = array(''); // add more controller name to exclude ssl.
if(!in_array($class,$exclude) && ($_SERVER['HTTP_HOST']!='localhost'))
{
// redirecting to ssl.
$CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
}
else
{
// redirecting with no ssl.
$CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
}
}
?>
Run the site. Your Site will now be forced to use SSL.
I am glad you read it all.
Thank you.

Manoj Bist

A Passionate Web Developer/Designer With over 6 years of experience in the industry, Manoj Bist is a seasoned professional who combines technical expertise with a down-to-earth demeanor. As a lover of both technology and design, he thrives on creating seamless digital experiences that captivate and inspire.

Leave a Reply

Your email address will not be published. Required fields are marked *