Top CodeIgniter Interview Questions and Answer.

There are given interview questions with answers on 20+ topics such as PHP, CodeIgniter, Laravel, OOP'S, SQL, PostGreSQL, Javascript, JQuery, Python etc. Each topic contains at least 25 interview questions with answers.

Codeigniter based on the MVC pattern is an open sourced framework which develops websites for PHP.  

Nows a days, Model View Controller(MVC) is the most popular design pattern in software development.

Codeigniter Framework provide predefine function and Library which are used for application development. codeigniter Framework also support HMVC.

 

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.



When a request comes from the CodeIgniter application, it will first go to the index .php page to routing to decide whether the request passes through cache or a security check. If the requested page doesn’t exist in the cache file, then routing will pass the request to security check. After testing the security check, the registered page will go to the application controller. The application controller is used to load the files like libraries, Models, Helpers, Plugins, and Scripts and then pass them to the View. A view is used to fetch the data from the application controller that will be presented to the user.



Helpers is collection of functions which help us with different tasks as name suggested. Every helper function is used to performs specific task with no dependence on other functions.

CodeIgniter provide various types of helper class like url_helper, captcha_helper ,email_helper. All these helpers are located in

system/helper

By default CodeIgniter does not load any Helper files. First step is to be load Helper. After loaded it is available in all controller and views.

To load helpers : 

$this->load->helper('name');

To load multiple helpers : 

$this->load->helper(array('helper1', 'helper2', 'helper3'));



Different types of helpers are as follows:

  • FILE HELPER: It helps to deal with the file.
  • TEXT HELPER: This is used to perform various text formatting routines.
  • FORM HELPER: It helps in creating form elements.
  • COOKIE HELPER: set and real cookies 
  • URL HELPER: It assists in creating links.



Libraries are packages that provide high-level abstractions. CodeIgniter provides a rich set of libraries. Libraries increase the speed of an application. The library is located in the System/Library.

 

Libraries can be loaded by using below code:

$this->load->library(‘Class_Name’);

Where Class_Name represents the name of the library.

Multiple Libraries can also be loaded by using following code:

$this->load->library->(array(‘library1′,’library2’));

 



LIBRARY 

  • The Library is a class. So, the user needs to make an instance of the class to use it.
  • Libraries are located under System/Libraries.
  • It is object-oriented.
  • A library can be loaded using $this->load->library (‘library name’).
  • To call library functions, the user needs to create an object of the class.

HELPERS 

  • A Helper is a file that has PHP functions.
  • Helpers are located under System/Helpers.
  • These are not written in an object-oriented format, hence the user can simply call helper functions.
  • A Helper can be loaded using $this->load->Helper (‘helper name’)
  • Helpers can be called in the same way you call PHP functions.



To load models in controller functions, use the following function:

$this->load->model(‘ModelName’);

If in case your model file is located in sub-directory of the model folder, then you have to mention the full path. For example, if your file location is application/controller/models/project/ModelName. Then, your file will be loaded as shown below :-

$this->load->model(‘project/ModelName’);



CodeIgniter allows for multiple database connections within a single application by defining each connection in the application’s database configuration file. To do this, you create an array with the database settings for each connection.

Here is an example of how to define two databases:

 

$db['default'] = array(

'dsn' => '',

'hostname' => 'localhost',

'username' => 'root',

'password' => '',

'database' => 'database_name1',

'dbdriver' => 'mysqli',

);

$db['second_db'] = array(

'dsn' => '',

'hostname' => 'localhost',

'username' => 'root',

'password' => '',

'database' => 'database_name2',

'dbdriver' => 'mysqli',

);



MVC stands for MODEL VIEW CONTROLLER. Model View Controller separates application logic from the presentation layer. It helps web pages to contain minimum scripting.

MODEL: It is used to represent data structures. Model classes constitute functions that help to insert, retrieve, and update information in the database.

CONTROLLER: It acts as an intermediary between the view, model, or any other resource to process HTTP requests. The Controller controls the whole application by URI.

VIEW: It represents the information that is being presented to the user. In CodeIgniter, a View could be a simple or complex webpage. The web page contains a header, footer, sidebar, etc. A view cannot be called directly.



All the markup files like header, footer, sidebar, etc are present in the view folder. In order to reuse them the programmer has to embed them in the controller file anywhere. This is to be done as they can't be called directly hence, they have to be loaded in the controller's file.

Load view in codeigniter:

$this->load->view('page_name');

 



The intermediary present between the models and the views to process the HTTP request and is used to generate a web page is known as a controller. It is basically known as the center of each request that exists on the web application of the user.

Syntax :

class ControllerName extends CI_Controller
{
    public function __construct()
    {
    parent::__construct();
    }
    public function MethodName()
    {
    
    }
}

 

By default, the file name is welcome.php that is known as the first page that is to be seen after installing CodeIgniter.

The programmer can generally change the default controller that is present in the file application/config/routes.php as per his/her need.

$route['default_controller'] = ' ';



CodeIgniter has a userfriendly URI routing rule so that we can re-route URL easily . There is a one-to-one relationship between a URL string and its corresponding controller class and its methods.

 

Routing is a technique through which we can converts SEO friendly URLs into a server code format that easily understandable.

We can manage these from  routes.php file at the located in application/config



You can follow these given steps to remove index.php from URL in Codeigniter.

 

1. Please open config.php

2. change from $config['index_page'] = "index.php" to $config['index_page'] = "";

3. Update also from $config['uri_protocol'] ="AUTO"; to $config['uri_protocol'] = "REQUEST_URI";

4. Put this code in your htaccess file

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

 



Hooks are the special feature of CodeIgniter that allows changing the inner functionality of the framework without making any change in core files of the framework. The hooks are prescribed in application/ hooks.php/config

 

These are the hook points available in Codeigniter:

  • pre_system - It is called during system execution.
  • pre_controller - This is called immediately before calling the controllers.
  • post_controller - constructor - This method is called instantly after the controller is instantiated but before calling any method.
  • post_controller - The post_controller hook is called immediately after the controller is fully executed.
  • display_override - This hook overrides the _display() method.
  • cache_override - This hook is used when there is a need to call our method instead of the method from Output Library called _display_cache(). It permits us to use your own cache display mechanism.
  • post_system - This hook is called when the final page is sent to the browser after the final execution.



The advantages are:

  • It provides extensive support across different library files
  • It is fast, reliable and light weighted and thus become more capable from the end-user perspective
  • It goes through different layers of security patches and it is considered to be the more secure framework from the developer perspective
  • It provides broad support across different database providers



The functions in Codeigniter are globally defined and freely available. Loading of libraries or helpers is not required when using these functions.

is_really_writable($file)

is_php($version)

html_escape($var)

config_item($key)

set_status_header($code[, $text = ”])

is_https()

remove_invisible_characters($str[, $url_encoded = TRUE])

is_cli() get_mimes()



The default timezone in Codeigniter is set by opening the application using the config.php file and adding this code to it.

date_default_timezone_set('your timezone');



The latest version of Codeigniter is 4.0, released on September 3, 2019.

 

The first way is to run the below code:  echo CI_VERSION;

The second way is to obtain the system/core/CodeIgniter.php directory and run the code given below:

define('CI_VERSION', '2.1.4');



The databases supported by Codeigniter Frameworks are:

  • MySQL (5.1+) via the MySQL (deprecated), MySQL and PDO drivers
  • Oracle via the oci8 and PDO drivers
  • PostgreSQL via the Postgre and PDO drivers
  • MS SQL via the MsSQL, Sqlsrv (version 2005 and above only) and PDO drivers
  • SQLite via the SQLite (version 2), sqlite3 (version 3) and PDO drivers
  • CUBRID via the Cubridand PDO drivers
  • Interbase/Firebird via the iBase and PDO drivers
  • ODBC via the ODBC and PDO drivers



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);



URL Routes needs to be configured because of the following reasons:

  • To improve the number of page visits.
  • To hide the code complexities from the user.



CodeIgniter Security methods help in creating a secure application. It has several ways of implementing security in the web application and protecting the raw input data fed to your program. Following are the CodeIgniter security methods:

  • XSS filtering (Cross-Site Scripting)
  • CSRF (Cross-Site Request Forgery)
  • Class-Reference.



CSRF can be activated by operating 

application/config/config.php file and setting it to

     $ config [‘csrf_protection’] = TRUE;



Codeigniter has got a cross-site scripting hack prevention filter. This filter either runs automatically or you can run it as per item basis, to filter all the POST and COOKIE data that come across.  The XSS filter will target the commonly used methods to trigger JavaScript or other types of code that attempt to hijack cookies or other malicious activity. If it detects any suspicious thing or anything disallowed is encountered, it will convert the data to character entities.



CodeIgniter provides an email library that simplifies the process of sending emails.

$this->load->library('email');

$this->email->from('your@example.com', 'Your Name');

$this->email->to('recipient@example.com');

$this->email->subject('Email Subject');

$this->email->message('Email content goes here.');

if (!$this->email->send()) {

// Email sending failed

} else {

// Email sent successfully

}



CodeIgniter provides a form validation library that simplifies handling form submissions. You can define validation rules for each form field and use the library’s functions to validate and retrieve the submitted data. Upon form submission, you can process the validated data within the controller and perform any necessary operations, such as storing data in the database.



CodeIgniter provides a form validation library that simplifies form validation. You can define validation rules for each form field and then use the library’s functions to validate and retrieve the validated data. Here’s an example:

$this->load->library('form_validation');

$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]'); $this->form_validation->set_rules('email', 'Email', 'required|valid_email'); if ($this->form_validation->run() == FALSE) { // Form validation failed } else { // Form validation succeeded }



In CodeIgniter, URLs are designed to be search-engine and user-friendly. CodeIgniter uses a segment-based approach rather than using a "query string" based approach.

http://www.example.com/student/edit/satyendra

The default URL pattern in CodeIgniter consists of 4 main components. They are:

Server name         : example.com

Controller             : user

Action or method  : edit

Parameter            : satyendra



There are three message types in Codeigniter:

Error Messages  : These are actual errors, such as PHP errors or user errors.

Debug Messages :These are messages that assist in debugging. For example, if a class has been initialized, you could log this as debugging info.

Informational Messages : .These are the lowest priority messages, simply giving information regarding some process.



For CodeIgniter, inhibitor is an error handler class that use native PHP functions like set_exception_handler, set_error_handler, register_shutdown_function to handle parse errors, exceptions, and fatal errors.



  • To Share this Link, Choose your plateform