In this example, we will use the CI third-party SSL helper to enforce an https or HTTP URI request and response between CI and the browser. This example will be constructed from the following helpers:
application/helpers/ssl_helper.php
: The CI helper for SSL that implements SSL on the links.application/controllers/helpersslexample.php
: This controller loads the helper and implements SSL on the links. The helper is loaded in the constructor.$this->load->helper('ssl'),
application/views/helper-ssl-view.php
: This is the rendered view that SSL is implemented on.Let us assume the URI to the project root is http://mydomain.com/myproject
. http://mydomain.com/myproject/helpersslexample
.
This CI helper file implements the services described in the preceding section. This helper uses the built-in CI URL library and URL helper using the redirect CI URL helper function.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'), if (!function_exists('force_ssl')) {function force_ssl(){ // get the CI instance to access the CI resources $CI =& get_instance();// Change the base_url to have https prefix $CI->config->config['base_url'] =str_replace('http://', 'https://',$CI->config->config['base_url']); if ($_SERVER['SERVER_PORT'] != 443){ // redirect CI to use https URI // so that ($CI->uri->uri_string() return // the current URI with https prefix redirect($CI->uri->uri_string());}}} if (!function_exists('remove_ssl')) {function remove_ssl(){$CI =& get_instance(); // Change the base_url to have http prefix $CI->config->config['base_url'] =str_replace('https://', 'http://',$CI->config->config['base_url']); if ($_SERVER['SERVER_PORT'] != 80){// redirect CI to use http URI // so that ($CI->uri->uri_string() return // the current URI with http prefix redirect($CI->uri->uri_string());}}}
Now we will see how the controller loads the SSL helper and calls its function force_ssl
to enforce the HTTPS URI request and response with the browser.
class Helpersslexample extends CI_Controller { public function __construct() { parent::__construct(); // Loading the ssl helper $this->load->helper('ssl'), // Enforce URI request of https force_ssl(); } /** * Index Page for this controller. * */ public function index() { $this->load->helper('url'), $this->load->view('helper-ssl-view'), } } /* End of file helpersslexample.php */ /* Location: ./application/controllers/helpersslexample */
The view file code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Menu</title> </head> <body> <table> <tr> <td> <a href="<?php echo site_url('welcome'), ?>"> Welcome - You are using https </a> </td> </tr> <tr> <td><a href="<?php echo site_url('example2/more/1/2/3'), ?>">Example2</a></td> </tr> </table> </body> </html>
3.12.153.212