×

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 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 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 Libraries

The library is an important part of the CodeIgniter framework. It has a large collection of libraries files that are used to increase the performance of an application. By default, all CodeIgniter libraries...

4 minutes read.

Installation of CodeIgniter

Before installing CodeIgniter, you need to make sure that the wamp or xampp server in the system is preinstalled. The installation procedure for CodeIgniter is very easy. You can download CodeIgniter by following these...

2 minutes read.

CodeIgniter Shopping Cart Class

It contains the various function that enables the user to add or update, display, and delete data item from the shopping carts while browsing the site. The items added in the cart...

10 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.

Structure of Codeigniter

The File structure of CodeIgniter is divided into three parts: ApplicationSystemuser_guide Application -: As the name represents Application, which contains all the main parts of the project like a controller, libraries, view, models, and others....

3 minutes read.

CodeIgniter Helpers

The Helpers (functions) are stored in the Helper file. It helps CodeIgniter to perform different tasks. The helper file is the collection of many functions that is used to perform specific task. It...

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 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.

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 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.

Directory Helper Codeigniter

Directory Helper CodeIgniter: provides a directory helper function that works with the directory. It shows the structure of the file, hidden file in the folder, and the folder in...

3 minutes read.

CodeIgniter URL Helper

The helper file contains some predefined functions that are used to work with URL, such as generate the current file path, transfer control, redirect, create a link, etc. Load the URL Helper Before using...

7 minutes read.

CodeIgniter Smiley Helper

The smiley helper file contains smiley images that are used in the application for showing emotions and comments while chatting with others. Load a Smiley Helper Before using Smiley Helper in the CodeIgniter application, you...

4 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 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.

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.

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.

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.