×

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

HTML Table Class CodeIgniter

HTML Table Class The CodeIgniter framework provides an HTML Table Class that is used to develop an auto-generated table using a defined array or result sets of the database table. Loading an HTML Table Class...

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

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.

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 Input Class

Input Class The CodeIgniter framework provides an input class that includes various input functions to pre-process global input data for protection; furthermore, it also provides some helper functions to obtain input data. This...

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

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.

CodeIgniter Email Class

CodeIgniter provides an e-mail library that helps to send a message from one application to another. You can create and send text messages easily in CodeIgniter application even you can set email...

9 minutes read.

CodeIgniter Cookie Helper

A cookie is a small set of files sent from the web server to the end-user system. In Helpers, the cookie helper file has some predefined functions that are used to the...

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

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 CAPTCHA Helper

A CAPTCHA (Complete Automated Public Turning test to tell Computer and Humans Apart) helper is a function that is used in web application to check whether the user is human or machine. It...

3 minutes read.

Image Manipulation Codeigniter

Image Manipulation A Codeigniter provides an image manipulation class that is used for resizing, cropping, rotation, and many other manipulation tasks. This class also support three major image libraries such as GD/GD2, NetPBM, and...

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

Retrieve data from Database

Retrieve data from the Database Now we will discuss how we can retrieve data from the database that we have inserted to the employees table of the database in our previous topic “inserted...

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

CodeIgniter Pagination Class

Pagination Class The CodeIgniter framework provides a pagination class that is used in the data list to create pagination links in a web application. Generally, it is used to retrieve data records from...

10 minutes read.

CodeIgniter User Agent Class

User Agent Class The CodeIgniter provides a user agent class that helps to identify and collect information about the browser, mobile devices, or robots visiting your site. Besides this, it is also used...

4 minutes read.