CodeIgniter Interview Questions

If you are an aspiring PHP Developer and have interviews lined up, go through these Codeigniter interview questions and answers that are frequently asked by interviewers of top companies. The following list of interview questions on Codeigniter covers the conceptual questions for freshers and experts and helps you answer different questions like directory structure of Codeigniter, the architecture of Codeigniter, MVC in Codeigniter, different libraries in Codeigniter, etc. Master the top Codeigniter interview questions and answers and crack your next PHP Developer, Backend Developer CodeIgniter interviews, and many more.

  • 4.5 Rating
  • 17 Question(s)
  • 10 Mins of Read
  • 3465 Reader(s)

Beginner

CodeIgniter is PHP opensource framework, based on loosely coupled MVC pattern. It consists of huge libraries, simple interface and logical structure to access these libraries, plugins, and helpers to solve complex logical problems. It’s a lightweight elegant framework which provides faster development rather than writing code from scratch. The latest version (as of now) is 3.1.10.

It’s appropriate in the following situations to create a project with CodeIgniter. 

  1. Small learning curve. 
  2. Situations where a framework with a small footprint is needed. 
  3. It’s a framework with zero configuration.
  4. It’s a framework which doesn’t require to stick to strict coding rules. 
  5. Provides high performance and simple coding structure. 
  6. It’s a framework which doesn’t use the command line. 
  7. It provides built-in protection against CSRF and XSS attacks.

CodeIgnitor directory structure consists of mainly 3 parts.

  • Application
  • System
  • Users_guide

Application is the main folder for developers where they can find all project files. It consists of models, views, controllers, configuration files, etc. All the project code, a developer works with will be in this directory. 

Main subdirectories of Application are cache, config, controller, core, helper, hooks, language, libraries, logs, model, views and third_party. 

Main subdirectories of System are core, database, fonts, helpers, language, libraries.

Inside users-guide, subdirectories which can be found are cilexer and source. It provides complete documentation of functions, libraries, and helpers of CodeIgnitor. A good resource if you stuck or don’t have much knowledge then follow users_guide. 

Source

Index.php files act as a front controller so requests first come here. It initialises base resources required to run Codeignitor. 

Now Router determines what should be done with requests. If a cache file exists for the request then information is directly passed to the browser and further process is ignored.   

If the cache doesn’t exist then before loading the application controller, HTTP requests pass through the security check. Index.php -> Route -> Security. 

Once the security check is done for submitted data, the request is passed to the Application controller. Application Controller loads all the necessary files like controller, model, view, libraries, helpers, etc and processes the request. Index.php -> Route -> Security -> Application Controller -> Models, Library
<- Helpers, Plugins

Now processed data from application controller has been sent to View. The view will provide the page with available data for caching so that further requests can be handled faster. 

Helper as the name suggests functions which aid to your program. Helper is simply a collection of functions in a particular category. There are various types of helpers like URL helpers, Form helpers, Text helpers, cookies helper, File helpers, etc.  

Helpers are independent procedural functions. A helper can be loaded in controller constructor which makes them available globally. A helper can be loaded like: 

$this->load->helper(‘file_name’); // It will load file helper.  
To load URL in helper use URL. $this->load->helper(‘url’);

To load multiple helpers : 

$this->load->helper->array(‘first_helper’,’second_helper’,’third_helper’);

 CodeIgnitor is based on MVC. Acronym for Model View Control. MVC separates application logic from presentation logic. As the presentation is separated from PHP logic so page contains less scripting and provides faster loading. 

Model represents data structures Model classes will contain functions that help to retrieve update and insert information into the database. 

Controller holds all application logic, serves as an intermediary between model and view and any other resources needed to process request. 

View is the information that is been passed to the user.  View is normally a web page but in CodeIgnitor it can be a part of a page like a header, footer, nav, etc.  

CodeIgnitor holds a loosely MVC approach. If your application doesn’t require a model, you can ignore them and can build an application with View and controllers.

The default URL structure for CodeIgniter is SEO and human-friendly. Codeignitor uses segment based approach over to query string. 

knowledgehut.com/interview-questions/codeignitor

The segments in the URL with the Model-View-Controller approach, usually represent:

knowledgehut.com/class/function/ID. Here Class which is our first segment represents controller class. Function Our 2nd segment represents which function or method of the controller to be called. 

ID Our 3rd segment represent that any additional ID or Parameter to be pass to the controller.

To access the URL pattern we need to use URI Library or URL Helpers available in codeignitor. 

By Default, Index.php is part of your URLs. Like 

knowledgehut.com/index.php/interview-questions/codeignitor

To remove index.php, if your apache has mod-rewrite enabled then modify the .htaccess file with simple rules.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Hooks provides a way in codeIgnitor to modify the inner working of a framework without hacking the core files of the framework. Codeingitor follows a specific process to execute request (explained in QA3) but there may be some instances when a developer wants to trick it. Hooks plays a vital role to deal with such situations. 

The hooks feature can be globally enabled/disabled by setting the 

$config['enable_hooks'] = TRUE; In the application/config/config.php file:

Hooks can be defined in the application/config/hooks.php file. Each hook is specified as an array in the following format. 

$hook['pre_controller'] = array(
        'class'    => 'MyClass',
        'function' => 'Myfunction',
        'filename' => 'Myclass.php',
        'filepath' => 'hooks',
        'params'   => array(param1, ‘param2’, 'param3')
);

Different types of hook points in codeIgnitor are: 

  • Post_controller_constructor
  • Pre_controller
  • post_controller
  • Pre_system
  • Post_system
  • Display_override
  • cache_override

Libraries are a feature-rich set of code for a particular functionality. CodeIgnitor provides a rich set of libraries which increases the development speed of application. Default libraries can be located at system/library directory. 

To Load single library please use  $this->load->library(‘class_name’);

To Load multiple libraries please use $this->load->library(array(‘class_name1’, ‘class_name2’, ‘class_name3’));

Custom libraries to be created in the application/libraries directory. 

If we want to add one or more methods to the existing library then it will replace the entire library with a modified version. Extending the library is a better option. There are rules to do the same. 

  • Class declaration must extend the parent class.
  • New class name and filename must be prefixed with MY_.classname.php

Helper in codeIgnitor helps you to accomplish different tasks.  Each helper file is a collection of functions which are aimed to solve a particular problem. Helpers are not written in an object-oriented way rather in a procedural way, independent of each other. 

Helpers can be of file helper, text helper, URL helper, form helper etc. 

To load helpers : $this->load->helper(‘helper_file_name’);  

To load multiple helpers : $this->load->helper(  array('helper1', 'helper2', 'helper3'));  

To auto load html helpers : Add in autoload.php $autoload['helper'] = array('html');  

To use the helpers we need to load it. CodeIgnitor will first look into application/helpers directory for the same and if it’s not found there then will look into system/helpers directory.

 In any dynamic application we need to call some function to get data from the database.  Model handles all data logic and representation and loads the data to view. 

<?php
Class FirstModel extends CI_Model {
function __Construct() {
parent::_construct();
}
}

FirstModel is the model name and same should be your file name. It extends the core codeIgnitor model which provides all the built-in functionality. 

To load a model use : $this->load->model('ModelName');

Manually connect database by adding $this->load->database();  in the page whereever required. 

Connect model to database : 

.Auto-connect feature helps to load database with every page load. To enable it add ‘database’ to array library autoload .php 

It will be like : $autoload[‘libraries’] = array(‘database’);

Controller is an intermediary between models and views. It processes HTTP requests and generates an HTML response. It’s the central part of every request coming to application. 

knowledgehut.com/interview-questions/codeignitor

Codeintor will try to find Interview-questions.php file and InterviewQuestions Class. 

Basic syntax of controller is like : 

<?php
defined(‘BASEPATH’) or exit(‘Direct script execution not allowed’’); 
Class First extends CI_Controller {
Public function index() {
//code goes here
}

Please note that filename here would be First.php and classname will be First.

Default controller for Codeigniter is Welcome.php which we can see post installation.

Like every other framework, codeIgnitor let you build the error reporting, also error logging class permits errors and debugging messages to be saved as a text file.  

Following are the common error logging functions: 

  • show_error(‘message’ [, int $statuscode= 500 ] ) : This function displays the error message supplied to it using application/errors/errorgeneral.php 
  • show_404(‘page’ [, ‘logerror’]) : This function will show 404 messages supplied to it by template application/errors/error404.php.
  • log_message(‘level’, ‘message’):  This function allows you to write messages to your log files. Mandatory param is error level and the second parameter is a type of message (Debug, Error or Info). 

To enable error logging you must set the threshold for logging in application/config/config.php. Also, your logs directory must be writable.

$config['log_threshold'] = 1;

Inhibitor is an error handling class in CodeIgniter. It uses PHP ‘s native functions like register_shutdown_function, set_exception_handler, set_error_handler to handle parse errors, exceptions, and fatal errors.

 Hooks are the events which can be called before or after the execution of a program. Hooks stored in a specific directory allows the codeIgnitor execution process without modifying core files. 

There are two hook files in CodeIgniter. One is application/config/hooks.php folder and other is application /hooks folder.

If a code is to be run every time with controller execution then you can write that in hooks. 

To enable Hook, go to application/config/config.php file and set it TRUE as shown below.

$config['enable_hooks'] = TRUE; 

To define a hook :

$hook['post_controller'] = array(  
            'class' => 'Classname',  
            'function' => 'functionname',  
            'filename' => 'filename.php',  
            'filepath' => 'hooks',  
            'params' => array('element1', 'element2', 'element3')  
            );  

Class: Name of your class defined in hooks.php file. 

Filepath: Here you have to mention the name of the directory which contains your script. Your script must be located inside the application folder. If your script is located in application/hooks folder, then your path will be simply hooked. But if your script is located in application/hooks/customfolder, then your path will be hooks/custom.

List of available hooks are : 

  • Pre_system
  • Pre_controller
  • Post_controller_constructor 
  • Post_controller
  • Display_override
  • Cache_override
  • Post_system

Sessions allows us to maintain the user “states” and helps to track user activity. In codeIgnitor session can be loaded with $this->load->library(‘session’);  post loading session library object we can use with $this->session.

To read the session data : $this->session->userdata(‘key’). 

Session data can also be get by $this->session->item

To create a session in codeIgnitor: Session’s Class set_userdata() method is used to create a session in CodeIgniter. This method takes an associative array containing your data that you want to add in session.

To add userdata one value at a time, set_userdata() also can be use with syntax:

$this->session->set_userdata('some_name', 'some_value');

To remove session data : It can be done with unset a particular key 

$this->session->unset_userdata('some_key');

Unset array of item keys : 

$array_items = array('username', 'email');
$this->session->unset_userdata($array_items);

If your CodeIgniter version is prior to 2.2, then one can get this error. The ideal solution is to upgrade CI to latest. If that’s not possible then edit the core/Common.php file and make the following change: 

$_config[0] = & $config; 
return $_config[0];

To use the config into the view following ways can be used. 

  1. Pass it through controller using load->view()
  2. With $this->config->item()
  3. With function config_item()

 Active record is a database design pattern, CI uses a modified version of it. The pattern allows data to be inserted, updated or deleted in the database with nominal scripting. The major benefit to using the Active Record features is that it allows you to create database independent applications since the query syntax is generated by each database adapter.

To get the raw query we can use $this->db->get_compiled_select(). Difference between get_compiled_select()  and last_query() is that get_compiled_select gives the query string generated even if we don’t run the query against database.

Description

CodeIgniter is a PHP driven framework with a very small footprint used for developing applications. It was created by EllisLab which is an open source framework has a very rich set of functionality and helps in increasing the speed of website development work. It will save you a lot of time if you are building a website from scratch.

CodeIgniter has become the first choice for developers for creating websites. Even though there are many other preferences when it comes to selecting the right programming framework for the apps, CodeIgniter has gained its own popularity. The only reason that most of the developers are using it because of the benefits that it offers to the people.

Nissan, Bonfire, Freedcamp, and Buffer, etc are the few websites using the CodeIgniter framework. There is a huge demand for PHP developers with CodeIgniter skills. As per Indeed average salary of "CodeIgniter developer" ranges from approximately $71,948 per year for Web Developer to $110,523 per year for Full Stack Developer.

To clear any interview, you must prepare well for an interview. After a lot of detailed research, we have brought you a hand-picked top CodeIgniter interview questions and answers to help to clear your interview. These interview questions on CodeIgniter for experienced and freshers alone will help you excel the CodeIgniter job interview and provide you with an edge over your competitors. Go through these questions and practice CodeIgniter interview questions and answers as much as possible.

Hope these interview questions and answers on CodeIgniter will help you to crack the interview. All the best!

Read More
Levels