×

CodeIgniter Security Class

Security Class

The security class provides various function that helps to create a secure application and process input data securely to the application. This class is preloaded in the CodeIgniter application, so you do not need to load it manually in the controller file.

The Function of the Security class

  1. XSS Filtering
  2. Cross-site request forgery (CSRF)

XSS Filtering

It is a cross-site scripting filter technique that is used to trigger JavaScript or other types of code that effort to destroy cookies or other malicious code. Furthermore, if any disallowed code is encountered, it can be called to the application by converting the data to the character entities.

It uses xss_clean() method to filter the data as follows:

$data = $this->security->xss_clean($data);

It is also used to protect images from potential XSS attacks during the transmission and uploading of image files to the server. It uses is_image as a second optional parameter in the XSS_clean method that protects an image file in the application from malicious attacks, so you need to set the TRUE value for the second parameter, and it returns a TRUE value instead of a string that indicates an image is safe. And when it encounters any malicious data in the browser, it returns FALSE.

if ($this->security->xss_clean($file, TRUE) == FALSE)
 {
   // define the false statement, if the file is not available.
 } 

Create a controller file Secure_controller.php and save it in application/controller/Secure_controller.php. After that, write the following program in the controller file.

Secure_controller.php

<?php
 defined( 'BASEPATH ') OR exit( 'No direct script access allowed');
 class Secure_controller extends CI_controller
 {
     public function cross()
     {   
         echo "<title> Tutorial and Example </title>"; 
          $data = "<script> Welcome to the world </script>";
 echo $this->security->xss_clean($data). "<br>";
 $is_image = 'images/my_pic.jpg';
 if ($this->security->xss_clean($data, $is_image = TRUE))
 {
     echo "file failed the XSS test"; 
 }
 else
 {
     echo "true";  
 }
 }
 ?> 

To run the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/index.php/Secure_controller/cross function; it shows the output, as shown below.

CodeIgniter Security Class

CSRF Protection

It stands for Cross-site request forgery, that protects user data from malicious attack by altering in the application/config/config.php file:

$config[ ‘csrf_protection’ ] = TRUE;

When you build a form using the form open() function in the form helper, it automatically inserts a secret CSRF field into the form. It also enables you to add the CSRF manually by using the get_csrf_hash() and get_scrf_token_name() function. A get_csrf_hash() function is used to return the hash value, whereas, get_csrf_token_name() return the name of the CSRF.

Example:

$csrf = array(
                         ‘name’ => $this->security->get_csrf_token_name(),
                         ‘$hash’ => $this->security->get_csrf_hash()
 );
 <input type = ”hidden” name =”<? echo $csrf[‘name’]; ?>” value =”<? echo $csrf[‘hash’]; ?>” />   

Create a controller file Secure_controller.php and save it in application/controller/Secure_controller.php. After that, write the following program in the controller file.

Secure_controller.php

<?php
 defined( 'BASEPATH ') OR exit( 'No direct script access allowed');
 class Secure_controller extends CI_controller
 {
   public function csrfdisplay()
 {                      
     echo "<title> Tutorial and Example </title>";
 $csrf = array(
 'name' => $this->security->get_csrf_token_name(), 
 'hash' => $this->security->get_csrf_hash('document'));
 print_r($csrf);
 }          
 }
 ?> 

To run the program in the localhost by invoking the URL localhost/CodeIgniter-3.1.11/index.php/Secure_controller/csrfdisplay function; it shows the output, as shown below.

CodeIgniter Security Class

Class References

  1. xss_clean(): It is used to clean the XSS exploit from the input data and return a clean string.

Syntax

xss_clean( $str, [ $is_image = TRUE ] );

It has two parameters:

$str: It contains an input string or an array of strings.

$is_image: It is an optional parameter. If you want to protect your image, set it to TRUE, and it returns a TRUE value that shows your image is safe; otherwise it returns FALSE.

  • sanitize_filename(): As the name suggests, a sanitize_filename () function helps to prevent directory or folder traversal and other security issues that are useful for specific files supplied via user input.

Syntax

sanitize_filename( $str [, $relative_path = FALSE ]);

It has two parameters:

$str: It contains the file name/path

$relative_path (bool): Uses a Boolean value to determine if you want to preserve the directory path in the file path.

  • get_csrf_token_name(): It is used to display the CSRF token name.

Syntax

get_csrf_token_name() 

or it can be set in the config file as $config[ ‘csrf_token_name’] value).

  • get_csrf_hash(): It is used to return the CSRF hash value.

Syntax

get_csrf_hash() 
  • entity_decode(): An entity_decode() function is used to detect the HTML entities until it encountered a semicolon.

Syntax

entity_decode ($str [, $charset = NULL ]);

It has two parameters:

$str: It takes input string.

$charset: It defines the character set as an input string to the security class.

  • get_random_bytes(): It is used to return the binary stream of random bytes, and if any error occurred, it returns FALSE.

Syntax

get_random_bytes ($length)

$length(int): It defines the Output length.


Related Topics

CodeIgniter Benchmarking Class

The CodeIgniter contains the Benchmarking class that is used to calculate the time difference between two points or the memory usage of the passed statements in the application. By default, the Benchmarking...

7 minutes read.

Migration Class CodeIgniter

The CodeIgniter framework provides the migration class that helps the web developers to create and handle databases in a structured and streamlined manner. The migration classes are very useful when more than...

6 minutes read.

CodeIgniter URI Class

URI Class The CodeIgniter contains a URI class that is used to retrieve information from URI strings. It also provides suitability to get information from the re-routed segments. The system automatically initializes this...

6 minutes read.

CodeIgniter Calendaring Library

The calendar library contains various functions that are used to create a dynamic calendar. It also enables you to pass the data to calendar cells and 100% control over the calendar design. Load...

7 minutes read.

CodeIgniter Date helper

A date helper file contains some predefined functions that work with date functions. Before using the date function in CodeIgniter, you have to load the date helper in the controller. For example: $this->load->helper(‘date’); Functions of...

12 minutes read.

How to remove an index.php file from the Codeigniter URLs?

As we know, a URL in CodeIgniter is designed in such a way that it would be search engine and human friendly, too, rather than using a standard approach to create a...

2 minutes read.

CodeIgniter HTML Helper

The HTML helper function is used in CodeIgniter to provide various functionality, such as headings, images, links, list tags, etc. Loading the HTML Helper Before using the html helper function, you must load the...

7 minutes read.

CodeIgniter Text Helper

The text helper contains the various function that is used to operate with text such as define a word limit and characters limit, conversion of word from ASCII to entities, etc. Loading the text...

4 minutes read.

Delete a record from Database CodeIgniter

Delete a record from the Database After inserting, retrieving, and updating table records, we will now learn how we can delete a particular record from a database table. To delete a record, first, we...

6 minutes read.

Download Helper Codeigniter

Download Helper Codeigniter: The download helper function is used to download data from the server to your computer. The data can be any format like text, jpg, mp3, mp4, etc. Loading...

2 minutes read.

Calendaring Class CodeIgniter

Calendaring Class The calendar library contains various functions that are used to create a dynamic calendar. It also enables you to pass the data to calendar cells and 100% control over the calendar...

6 minutes read.

CodeIgniter Controller

As its name suggest that it is a Controller that controls the web application, and it works as an intermediary between the Models and the View. A controller takes requests from the user...

3 minutes read.

CodeIgniter Number helper

The number helper file contains some predefined function that deals with numeric data to display numbers in bytes format. Load a Number Helper You must load a number helper file in the controller to perform...

3 minutes read.

Insert data to the database CodeIgniter

After successfully creating a database connection with the CodeIgniter application, we will now understand how we can insert records into the database. To insert a record into a database table, Codeigniter provides...

8 minutes read.

CodeIgniter Language Class

Language Class The CodeIgniter’s language class contains the various functionality that is used to access the language-specific files and text line for the purposes of internationalization. This class provides you suitability to add or...

4 minutes read.

CodeIgniter Security Helper

A Security helper file contains some predefined functions that are used to protect application from unauthorized access. Loading the Helper The following syntax is used to load the security helper in the CodeIgniter application. Syntax $this-> load->...

4 minutes read.

CodeIgniter String Helper

The string helper file contains functions that allows separate operations with strings in CodeIgniter. Loading the String Helper Before using the string helper in the CodeIgniter application, you must load it in the controller...

7 minutes read.

Codeigniter Session Library

Session Library The session is an essential part of any application. It contains various functions to manage the users' status and track their activity while browsing on the site. For example,...

13 minutes read.

CodeIgniter Routes

The Routes are used to handle URL requests on the browser. It matches the URL request to the predefined routes in CodeIgniter. Therefore, a file must be predefined as a routes.php file to...

6 minutes read.

CodeIgniter Output class

Output class The CodeIgniter framework contains a core class that is an Output class. It  includes the various functions that are used to send the final web page to the requesting browser. In...

8 minutes read.