How to force ssl in codeigniter?

by giovanny.lueilwitz , in category: PHP Frameworks , 4 months ago

How to force ssl in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 3 months ago

@giovanny.lueilwitz 

To force SSL in CodeIgniter, you can edit the config file and add the following lines of code:

  1. Open the config file located at application/config/config.php
  2. Search for the following line of code:
1
$config['base_url'] = '';


  1. Replace it with the following code to force SSL:
1
2
3
4
5
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
    $config['base_url'] = 'https://'.$_SERVER['HTTP_HOST'].'/your_project_name/';
} else {
    $config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/your_project_name/';
}


Replace 'your_project_name' with the name of your project directory. This code checks if the HTTPS protocol is enabled and sets the base URL accordingly.

  1. Additionally, you can force SSL on specific controllers or functions by adding the following code at the beginning of the controller or function:
1
2
3
4
if ($_SERVER['HTTPS'] != "on") {
    redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}


This will redirect the user to the SSL version of the page if they access it using an insecure connection.


By following these steps, you can force SSL in your CodeIgniter application to enhance security and protect sensitive information.