CodeIgniter Hooks

In CodeIgniter, hooks are events which can be called before and after the execution of a program. It allows executing a script with specific path in the CodeIgniter execution process without modifying the core files.

For example, it can be used where you need to check whether a user is logged in or not before the execution of controller. Using hook will save your time in writing code multiple times.

There are two hook files in CodeIgniter.
1. is application/config/hooks.php file
2. is application /hooks folder.

Step 1 :How to Enabling Hooks

Go to application/config/config.php file and set it TRUE as shown below.

$config[‘enable_hooks’] = TRUE;

Step 2 :Defining a Hook

A hook can be defined in the application/config/hooks.php file. Each hook is defined as an array consisting of the following terms.

$hook[‘pre_controller’] = array(
class‘    => ‘Blocker’,
function‘ => ‘requestBlocker’,
filename‘ => ‘Blocker.php’,
filepath‘ => ‘hooks’,
params‘   => “”
);

Step 3 : Creating Hook file

Once I want to allow only one ip address to hit my codeigniter application

create file inside /application/hooks/Blocker.php

<?php
class Blocker {

function Blocker(){
}
function requestBlocker(){
if($_SERVER[“REMOTE_ADDR”] != “127.0.0.1“){
echo “not allowed”;
die;
}
}
}
?>