Google News
logo
CodeIgniter Interview Questions
Codeigniter is a programming framework for developing web applications on PHP
 
CodeIgniter is a programming framework that allows the rapid development of highly dynamic websites using the PHP language. It was developed by EllisLab, a software development company, and first released publicly in 2006.
 
The framework is available as open-source software under the MIT License and follows the model-view-controller (MVC) structure for web development. It also has a very small footprint, taking up very little space on the computer/server.
CodeIgniter was created by EllisLab and is now a project of the British Columbia Institute of Technology. The first public version of CodeIgniter was released on February 28, 2006.
A list of most important features of CodeIgniter :
 
* It is open source under the MIT License.
* It is an open source framework and free to use.
* It is extremely light weighted.
* It has easy-to-read-and-use documentation
* It is based on the Model View Controller (MVC) pattern.
* It has full featured database classes and support for several platforms.
* It is extensible. You can easily extend the system by using your libraries, helpers.
Hooks are a feature in codeigniter which help the user to change the inner working without having to change the core files. They are represented by application/config/hooks.php. file. Hooks are more often to be used in executing a script with a particular path within codeigniter.  
Helpers is the feature in codeigniter where it assists the user in performing specific function. The helper will vary according to the function it’d be assisting such as url helpers will assist in creating links whereas text helpers assist in performing text formatting routines.
To load a file in codeigniter you use
 
$this->load->model (‘Model_Name’);
Routing is defined as serving PHP files in an alternative way rather than accessing it from the browser. This allows the user to gain unlimited freedom in customizing the default URL pattern to fit his own requirement.
DataMapper : An Object Relational Mapper written in PHP for CodeIgniter. It is designed to map your Database tables into easy to work with objects, fully aware of the relationships between each other.
 
Gas ORM : A lightweight and easy-to-use ORM for CodeIgniter. Gas was built specifically for CodeIgniter app. It uses CodeIgniter Database packages, a powerful DBAL which support numerous DB drivers. Gas ORM provide a set of methods that will map your database tables and its relationship, into accessible object.
Finding out the version can be done in two ways.
 
The first way is to run the below code:
<?php echo CI_VERSION;?>
The second way is to obtain the system/core/CodeIgniter.php directory and run the code given below :
define('CI_VERSION', '3.0.0');
or
define('CI_VERSION', '3.0.1');
.
.
.
define('CI_VERSION', '3.1.0');
Commonly asked CodeIgniter Interview Questions will feature this topic- Following are the most common databases that can be used with CodeIgniter :
 
MySQL
ORACLE
SQLite
ODBC
FIREBIRD
CUBERID etc.
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.
The architecture of Codeigniter has three essential points :
 
* It is dynamically instantiated, making it incredibly lightweight.

*
The components in Codeigniter are independent, making it loosely coupled.

*
Every component has its singularity, as every class and function focuses on its purpose.
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()
Helpers : Helpers are just small functions that help you avoid repetitive code and produce standard results. Whereas libraries contain classes, can include different files, talk to database etc.
 
Library : Library is used in object oriented context (Controller, …), while a helper is more suitable to be used within the Views (non object oriented).

Helper, Plugin and Library :

Since all three methods achieve the same ends. The question then is when do you use what?
 
Fortunately, CI has also provided that distinction in their user guide which you can go read it yourself.
 
For me, these are my guidelines on when to use what :

1. Plugins : I put all 3rd party codes I’m using in my application as Plugins. I would, as best as I can, try to use classes rather than straight function calls.

2. Helpers : Any standalone straight functions calls, which are repetitive in nature, I classify them as Helpers. For example, sorting functions, my own calculation functions, etc

3. Libraries : I classify my own classes as ‘Libraries’. Normally, if I’m already writing a class in my application, it would then to be the core logic of the application, as such, I group them all in the Library folder.
Application flow chart from Codeigniter documentaion

* The index.php serves as the front controller, initializing the base resources needed to run CodeIgniter.
* The Router examines the HTTP request to determine what should be done with it.
* If a cache file exists, it is sent directly to the browser, bypassing the normal system execution.
* Security. Before the application controller is loaded, the HTTP request and any user submitted data is filtered for security.
* The Controller loads the model, core libraries, helpers, and any other resources needed to process the specific request.
* The finalized View is rendered then sent to the web browser to be seen. If caching is enabled, the view is cached first so that on subsequent requests it can be served.
To prevent hacking and other malicious activities codigniter applies a cross site scripting hack filter which will automatically start to filter all post and cookie data while comparing it to existing methods that are used to trigger javascript and once an anomaly is detected it is automatically converted into character entries.  
To link images from a view in a codeigniter first use an absolute path to the resources required and link the image from a view in codeigniter /css/styles.css /js/query.php /img/blog/sample.jpg
Inhibitor is a specialist class in codeigniter which primarily functions as a means to combat or handle errors and is primarily comprised of functions such as set_exception_handler set_error_handler register_shutdown_function which are useful in handling parse errors exceptions and fatal errors.  
The default URL patter in codeigniter is split up into four functions which start with the server name, controller class, controller name and finally function parameters To accesses the URL pattern in codeigniter you have to use a URL helper.  
Model's responsibility is to handle all data logic and representation and load data in the views. It is stored in application/models folder.
 
The basic structure of a model file :
class ModelName extends CI_Model {
  function_construct()
        {
          parent::_construct();
        }
}     
Here, ModelName is the name of your model file. Remember, the class first letter must be in an uppercase letter followed by other lowercase letters, and it should be the same as your file name. It extends the base CodeIgniter Model so that all the built-in methods of parent Model file gets inherited to the newly created file.
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');
To extend a native input class the user must first build a file which is to be named application/core/MY_Input.php And then proceed to declare the class with Class MY_Input extends CI_Input { }
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');
To link or add the images/CSS/JavaScript in Codeigniter absolute path to your resources is used.
 
For example :
// Refers to $config['base_url']
<img src="<?php echo site_url('images/myimage.jpg'); ?>" />
Sessions in CodeIgniter are the classes that help maintain a user's "state" and track their activity when they browse the website.
 
To use the session, the Session class is to be loaded in the controller.
$this->load->library(‘session’);
sessions in Codeigniter use this method.
$this->load->library('session');
The Sessions library object will be available to use once the files are loaded :
$this->session
The DB Class insert_id() method is used in Codeigniter to get the last insert id.
 
Usage :
function add_post($post_data){
$this->db->insert('posts', $post_data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
* CLI is a text-based command-line interface that can interact with computers through a defined set of commands.

* CLI in Codeigniter is used for the following purposes
 
* To run cron-jobs without using wget or curl.
* To make cron-jobs inaccessible from being loaded in the URL by checking the return value of is_cli().
* To make interactive "tasks" to perform tasks like run backups, set permissions, snip cache folders, etc.
* CLI also helps in integrating Codeigniter with other applications in different languages. For example, a random C++ script could call a command and run code in models.
The is_cli() method in the Codeigniter checks if the request is originated from the command line or not.
 
It returns TRUE if the application is run through the command line and FALSE if not.
* A driver is a type of library that has a parent class and multiple child classes. These child classes can access their parent class, but they can’t access their siblings.

* Drivers can be found in the system/libraries folder.

* There are three steps for creating a driver :
* Making file structure
* Making driver list
* Making driver(s)
* You need to load the helper files for using it. Once loaded, it will be globally available to your controller and views. They can be obtained at two places in CodeIgniter. A helper file will be searched by CodeIgniter in the application/helpers folder and if it is not available in that folder then it will check in the system/helpers folder.

* Helper file can be loaded by adding the following code to the constructor of the controller or inside any function that wants to use: $this->load->helper('file_name');
Write your file name at the place of file_name.

* To load URL helper we can use the code given below: $this->load->helper('url');

* You are allowed to auto-load a helper if your application needs that helper globally by including it in the application/config/autoload.php file.

* Loading multiple helpers is also possible. For doing this, specify them in an array as given below:
$this->load->helper(  
   array('helper1', 'helper2', 'helper3')  
);  
Few advantages of using CodeIgniter is given below :
 
Built-in libraries : It comes with various types of default helpers for multiple things including strings, arrays, cookies, directories, file handling, and forms among others.

Data abstraction : You can make use of the CodeIgniter database abstraction layer for creating, adding, deleting, and replacing statements in a hassle-free manner. This framework allows you to manage multiple connections using a single application.

Active Developer Community : Bigger the community, the better the help you get. Newly graduated developers look forward to the framework’s forum to get their doubts solved and learn about new things in the process. With so many people actively participating in it from around the world, your doubts will be solved within few hours. And due to the same reason, CodeIgniter documentation is 10 times bigger than any other framework.

Collaboration with Expression Engine : The collaboration permits developers using CodeIgniter to use libraries and everything else provided by Expression Engine and vice versa. Because of this, developers will get few benefits like better parser class, improved built-in user authentication, and easy access to modular applications.

Security : The security strength modification can be done according to your client’s needs. These changes are made when the system is initialized by switching off the magic_quotes_runtime directive irrespective of the register_globals directive. You don’t need to remove the slashes during information retrieval from the database. You can enable encryption of cookies, where you can handle databases and escape SQL queries directly.

Immigration Features : Database schema update management is easier over different fields by using the migration aspect. It is an easier process to immigrate from the server to the server in Codeigniter.

Easy to Use : It is easier to use compared to other popular frameworks such as Symfony, Zend framework, and Cake PHP.
* CSRF(Cross-Site Request Forgery) token is a randomly generated value that gets modified with every HTTP request sent by webform.

* A CSRF attack forces a browser of the logged-on victim for sending a forged HTTP request, including the session cookie of the victim and other information related to authorization, to a web application. A CSRF token is used for setting or activating the protection in CodeIgniter.

* CSRF token is saved in the user’s session when it is added in the website form. When we submit the form, the website compares both submitted tokens and saved tokens in the session. If they are the same, a request is considered valid. When the page gets loaded token value will also be changed each time. Thus it becomes difficult for the hackers to identify the current token.

* To set CSRF, you have to set the corresponding config value as true in your application/config/config.php file.
Syntax : $config['csrf_protection'] = TRUE;

* If you use the form helper, the form_open() method will automatically insert a hidden CSRF field in your forms.
The file specified in the default controller loaded by default when no file name is mentioned in the URL. By default, it is welcome.php which is the first page to be seen after installing CodeIgniter.
 
With URL
localhost/codeigniter/  
Welcome.php will be loaded as there is no file name mentioned in the URL.
 
Although as per your need, you can change the default controller in the file application/config/routes.php.
$route['default_controller'] = ' ';  
Here, specify your file name which you want to be loaded by default.
The Second segment of URI determines which method is being called. If you want to override it, you can use _remap() method. The _remap method always get called even if URI is different. It overrides the URI.

For Example :
public function _remap($methodName)  
{  
            if ($methodName === 'a_method')  
            {  
            $this->method();  
            }  
            else  
            {  
            $this->defaultMethod();  
            }  
}
To load multiple helper files, specify them in an array,
$this->load->helper(  
 array('helper1', 'helper2', 'helper3')  
);
There are three methods to create a library,
 
* Creating an entirely new library
* Extending native libraries
* Replacing native libraries
Yes, we can add some extended functionality to a native library by adding one or two methods. It replaces the entire library with your version. So it is better to extend the class. Extending and replacing is almost identical with only following exceptions.
 
* The class declaration must extend the parent class.
* New class name and filename must be prefixed with MY_.

For example, to extend it to native Calendar, create a file MY_Calendar.php in application/libraries folder. Your class declared as class MY_Calendar extends CI_Calendar}
To connect more than one database simultaneously, do the following,
$db1 = $this->load->database('group_one', TRUE);  
$db1 = $this->load->database('group_two', TRUE);  
CodeIgniter security methods help to create a secure application and process input data. The methods are given below :
 
* XSS filtering
* CSRF (Cross-site Request Forgery)
* Class reference
XSS stands for cross-site scripting. Codeigniter contains a cross-site scripting hack prevention filter. The XSS filter targets methods to trigger JavaScript or other types of suspicious code. If it detects anything, it converts the data to character entities.
 
XSS filtering uses xss_clean() method to filer data.
$data = $this->security->xss_clean($data);  
There is an optional second parameter, is_image, which is used to test images for XSS attacks. When this parameter is set to TRUE, it doesn't return an altered string. Instead, it returns TRUE if an image is safe and FALSE if it contains malicious information.
if ($this->security->xss_clean($file, TRUE) === FALSE)  
    {  
        //file failed in xss test  
    }​
 
You can enable protection by editing config.php file and setting it to
 
To enable CSRF make the following statement TRUE from FALSE in application/config/config.php file.
$config['csrf_protection'] = TRUE;
There are the various ways by which, we can prevent CodeIgniter from CSRF. The most used method is using the hidden field in each page of the website. The hidden field is stored in the user's session. The filed is changed with every HTTP request. The user can be detected in its every request to the website. The hidden value is always compared with the one saved in the session. If it is the same, the request is valid.
A CSRF attack forces a logged-on victim's browser to send a forged HTTP request, including victim's session cookie and other authentication information, to a web application.
 
For example, suppose you have a site with a form. An attacker could create a bogus form on his site. This form could contain hidden inputs and malicious data. This form is not sent to the attacker's site, in fact, it comes to your site. Thinking that the form is genuine, your site process it.
 
Now suppose that the attacker's form point towards the deletion form in your site. If a user is logged in and redirected to the attacker's site and then perform the search, his account will be deleted without knowing him. That is the CSRF attack.
To protect from CSRF, we need to connect both HTTP requests, form request and form submission. There are several ways to do this, but in CodeIgniter hidden field is used which is called the CSRF token. The CSRF token is a random value that changes with every HTTP request sent.
 
With each request, a new CSRF token is generated. When an object is created, name and value of the token are set.
$this->csrf_cookie_name = $this->csrf_token_name;  
$this->_csrf_set_hash();​

 

The function for it is,
function _csrf_set_hash()  
{  
      if ($this->csrf_hash == '')  
        {  
if ( isset($_COOKIE[$this->csrf_cookie_name] ) AND  
             $_COOKIE[$this->csrf_cookie_name] != '' )  
           {  
             $this->csrf_hash = $_COOKIE[$this->csrf_cookie_name];  
          } else {  
               $this->csrf_hash = md5(uniqid(rand(), TRUE));  
         }  
       }  
    return $this->csrf_hash;  
}​
Anchor tag creates a standard HTML anchor link based on the URL of your local site.
Syntax :
anchor($uri = '', $title = '', $attributes = '')
Here, $uri represents a URI string, $title represents an anchor title and $attributes represents an HTML attributes. It returns an HTML hyperlink (anchor tag) of string type.

The first parameter can have any segments you would like to append to the URL. These segments can be a string or an array.
 
The second parameter is the text that will be displayed with a link. The URL will be used in case you leave it blank.
 
The third parameter can contain an attribute list you would like added to the link. The attributes can be a string or an associative array.
 
Example :
echo anchor('details/local/123', 'My Details', 'title="Details title"');
// Prints: <a href="http://example.com/index.php/details/local/123" title="Details title">My Details</a>
* Features of Email Class in CodeIgniter are given below:
* Multiple protocols such as Mail, Sendmail, and SMTP
* TLS and SSL Encryption for SMTP
* CC and BCCs
* Multiple recipients
* Attachments
* HTML or Plain-text email
* Priorities
* Word wrapping
* BCC Batch Mode, enabling larger e-mail lists to be broken into smaller BCC batches
* Email Debugging tools

Sending Email :
Sending an email is a simple process here. You can configure an email on the fly or set your preferences in the app/Config/Email.php file. A basic example for demonstrating how you might send email is given below:
$email = \Config\Services::email();
$email->setFrom('your@interviewbit.com', 'Your Name');
$email->setTo('someone@interviewbit.com');
$email->setCC('another@another-example.com');
$email->setBCC('them@their-example.com');
$email->setSubject('Email Test');
$email->setMessage('Testing the email class.');
$email->send();​
CodeIgniter enables you to develop error reporting into your applications by using the below-given functions. Also, it has a class dedicated to error logging that permits messages related to error and debugging to be saved as text files.
 
Functions related to error handling are :
 
This function will display the error message provided by the application/errors/errorgeneral.php template.
show_error(‘message’ [, int $statuscode= 500 ] )​
This function shows the 404 error message supplied to it by using the application/errors/error404.php template.
show_404(‘page’ [, ‘logerror’])​

 

This function permits you to write messages onto your log files. You must provide anyone among three “levels” in the first parameter that indicates the message type (debug, error, info), with the message itself in the second parameter.
log_message(‘level’, ‘message’)​