Wednesday, 12 July 2017

CodeIgniter Interview Questions


1.Explain CodeIgniter architecture.?

ANS :

Data flow in CodeIgniter

1.The index.php serves as the front controller, initializing the base resources needed to run CodeIgniter. 


2. The Router examines the HTTP request to determine what should be done with it. 

3. If a cache file exists, it is sent directly to the browser, bypassing the normal system execution.

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

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

2.What is routing and Give me an example?

ANS : 
  Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. 
   Setting your own routing rules. Routing rules are defined in your application/config/routes.php file. In it you'll see an array called $route that permits you to specify your own routing criteria

Ex:  In application/config/routes.php file

 $route
['product/(:any)'] = 'catalog/product_lookup';
A URL with “product” as the first segment, and anything in the second will be remapped to the “catalog” class and the “product_lookup” method.

if you don't know how many parameters you would like to pass you could try

   $route['login/(:any).*'] = 'home/bacon/$1'
 Benefits of  routing :  
  • From SEO point of view, to make URL SEO friendly and get more user visits
  • Hide some URL element such as a function name, controller name, etc. from the users for security reasons
  • Provide different functionality to particular parts of a system
 ANS:-
A CodeIgniter helper is a set of related functions (Common functions) which you could use them within ModelsViewsControllers,.. everywhere.But a Library is a class, which you need to make an instance of the class (by $this->load->library()).

exp helpers: 1.array, 2.captcha  3.url 4.html 5.email 6.date  7.file 8.form 9.string 10.download

Exp library : 1.Email 2.From_validation 3.Pagination 4.Table 5.Upload 6.image_lib 6.Calendar 7.zip
                   8.Encrypt   9.Driver 10.session


4.What is hooks in codeigniter ?

Ans: 
     Codeigniter’s hooks feature provides a way to change the inner working of the framework without hacking the core files.In other word, hooks allow you to execute a script with a particular path within the Codeigniter.
it is defined in application/config/hooks.php file.

The hooks feature can be globally enabled/disabled by setting the following item in the application/config/config.php file:
$config[‘enablehooks’] = TRUE;
 Ex:  A hook can be defined in the application/config/hooks.php file. Each hook is defined as an array consisting of the following terms.
      
  1. $hook['pre_controller'] = array(  
  2.             'class' => 'Classname',  
  3.             'function' => 'functionname',  
  4.             'filename' => 'filename.php',  
  5.             'filepath' => 'hooks',  
  6.             'params' => array('element1''element2''element3')  
  7.             );  


5.List out different types of hook point in Codeigniter?

 ANS:
  • post_controller_constructor  -- It is called immediately after your controller is started, but before any method call.
  • pre_controller  -- It is called immediately prior to your controller being called. At this point all the classes, security checks and routing have been done.
  • post_sytem -- It is called after the final page is sent to the browser at the end of the system execution.
  • pre_system -- It is called much before the system execution. Only benchmark and hook class have been loaded at this point.
  • cache_override -- It enables you to call your own function in the output class.
  • display_override -- It is used to send the final page at the end of file execution.
  • post_controller -- It is called immediately after your controller is completely executed.

6.XSS Filtering

CodeIgniter comes with a Cross Site Scripting prevention filter, which looks for commonly used techniques to trigger JavaScript or other types of code that attempt to hijack cookies or do other malicious things. If anything disallowed is encountered it is rendered safe by converting the data to character entities.
To filter data through the XSS filter use the xss_clean() method:
$data = $this->security->xss_clean($data);
An optional second parameter, is_image, allows this function to be used to test images for potential XSS attacks, useful for file upload security. When this second parameter is set to TRUE, instead of returning an altered string, the function returns TRUE if the image is safe, and FALSE if it contained potentially malicious information that a browser may attempt to execute.

Cross-site request forgery (CSRF)

You can enable CSRF protection by altering your application/config/config.php file in the following way:
$config['csrf_protection'] = TRUE;
If you use the form helper, then form_open() will automatically insert a hidden csrf field in your forms. If not, then you can use get_csrf_token_name() and get_csrf_hash()
$csrf = array(
        'name' => $this->security->get_csrf_token_name(),
        'hash' => $this->security->get_csrf_hash()
);

...

<input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" />
Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF cookie. The default regeneration of tokens provides stricter security, but may result in usability concerns as other tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc). You may alter this behavior by editing the following config parameter

      $config['csrf_regenerate'] = TRUE;


7. Explain what is inhibitor in CodeIgniter?

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

8.Explain how you can extend the class in Codeigniter?

To extend the native input class in CodeIgniter, you have to build a file named application/core/MY_Input.php and declare your class with
Class MY_Input extends CI_Input {
}

9.Explain how you can prevent CodeIgniter from CSRF?

There are several ways to protect CodeIgniter from CSRF, one way of doing is to use a hidden field in each form on the website.  This hidden field is referred as CSRF token; it is nothing but a random value that alters with each HTTP request sent. As soon as it is inserted in the website forms, it gets saved in the user’s session as well.  So, when the form is submitted by the users, the website checks whether it is the same as the one saved in the session. If it is same then, the request is legitimate.

10.Explain how you can enable CSRF (Cross Site Request Forgery) in CodeIgniter?

You can activate CSRF (Cross Site Request Forgery) protection in CodeIgniter by operating your application/config/config.php file and setting it to
$config [ ‘csrf_protection’] = TRUE;
If you avail the form helper, the form_open() function will insert a hidden csrf field in your forms automatically

11.How to access config variable in codeigniter?

$this->config->item('variable name');

12.How to unset session in codeigniter?

 $this->session->unsetuserdata('somename');

13.How do you get last insert id in codeigniter?

 $this->db->insertid();;

14.How to print SQL statement in codeigniter model??

 $this->db->lastquery();

15.How you will work with error handling in codeigniter?

ANS: CodeIgniter lets you build error reporting into your applications using the functions described below. In addition, it has an error logging class that permits error and debugging messages to be saved as text files.
show_error(‘message’ [, int $statuscode= 500 ] )
This function will display the error message supplied to it using template application/errors/errorgeneral.php.
show_404(‘page’ [, ‘logerror’])
This function will display the 404 error message supplied to it using template application/errors/error404.php.
log_message(‘level’, ‘message’)
This function lets you write messages to your log files. You must supply one of three “levels” in the first parameter, indicating what type of message it is (debug, error, info), with the message itself in the second parameter.

16.How to get random records in mysql using codeigniter?

We can use this:
$this->db->order_by(‘id’,’RANDOM’);

17.Why codeigniter is called as loosely based mvc framework?

Reason behind this is we does not need to follow strict mvc pattern while creating application.We can also able to build with model only view and controllers are enough to built a application.

Calling model from view :
        $CI =& get_instance();
$CI->load->model('Home_model');
$result= $CI->Home_model->getmenu();    
  
 Here get_instance() function returns the main CodeIgniter object.

18.what is the use of _remap in codeIgniter using php
ANS:  Remapping Function Calls

If your controller contains a function named _remap(), it will always get called regardless of what your URI contains. It overrides the normal behavior in which the URI determines which function is called, allowing you to define your own function routing rules.
For example: your url is localhost/index.php/user/index and you don't want to call index for this then you can use _remap() to map new function view instead of index like this.
public function _remap($method)
{
    if ($method == 'index')
    {
        $this->view();
    }
    else
    {
        $this->default_method();
    } 
}                 

19.How do I call one Controller’s methods from a different Controller?

ANS:  You can do like
$result= file_get_contents(site_url('[ADDRESS TO CONTROLLER FUNCTION]'));
Replace [ADDRESS TO CONTROLLER FUNCTION] by the way we use in site_url();
You need to echo output in controller function instead of return.
-------------------------
If you want common functionality, you should build a library to be used in the two different controllers.
-------------------------
1. Controller A 
   class A extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }
    function custom_a()
    {
    }
}

2. Controller B 

   class B extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }
    function custom_b()
    {
            require_once(APPPATH.'controllers/a.php'); //include controller
            $aObj = new a();  //create object 
            $aObj->custom_a(); //call function
    }
}

------------------------Use the $CI = get_instance() trick
-------------------------------------------

20.Can I extend the core Database class?

No, you can not. This is quite explicitly described in the Creating Libraries section of the user guide: [quote] The Database classes can not be extended or replaced with your own classes, nor can

21.Is there a way to cycle $this->input->post() items?

There are no CodeIgniter functions to do this, but you can accomplish this easily with a construct such as this one. The result of this function is a $safe_post_array that contains all posted data

22.What is the difference between set_flashdata and set_userdata?

set_userdata is for adding session data.
set_flashdata is for adding session data that will only be available for the next request, and is then automatically cleared.

23.CodeIgniter calling model on view?

<?php
$CI =& get_instance();
$CI->load->model('MyModel');
$result= $CI->MyModel->MyMethod($parameter)->result_array();        
  foreach($result as $row){ 
         echo $row['column_name'];                      
    }

24. How can you show web page bench marks in codeignniter ?
     If you write this line of code in controller then you will get the bench marks.
         $this->output->enable_profiler(TRUE);

  Note : This class does NOT need to be initialized. It is loaded automatically by the Output Class if profiling is enabled as shown below.

25.How to load model with allias name ?

Ans :      we have to write this constructor in controller.
         
    public function __construct() {
        parent::__construct();
               $this->load->model('User_model', 'umodel');
    }


we can call User_model like below.
      

          $this->umodel->doRegister();
     

26. How to Disable Apache web Directory Listing Using .htaccess file?
ANS:  add below line of code in  .htaccess file.

      Options -Indexes
 Ref: https://www.tecmint.com/disable-apache-directory-listing-htaccess/


27.
  How to use single codeigniter instance for multiple Applications ? 

ANS:  we have to fellow below steps
     i). Download codeigniter 3 instance  and rename application folder  like frontend and backend please check below figure.




    ii). Rename index.php file as frontend.php and backend.php
     iii). Create new controller  i.e Backend.php in application/backend/controllers
     iv). Create New Controller i.e Frontend.php in application/frontend/controllers
    v). Add below code in .htaccess file.    
       RewriteEngine on  
       RewriteRule ^frontend$ frontend.php [L]
       RewriteCond %{REQUEST_FILENAME} !-f 
       RewriteRule ^(.*)$ backend.php/$1 [L]
 
28. How to connect multiple databases in codeigniter ?
Ans:  Step1: add below code  in application/config/database.php file
                 
$db['default'] = array(
               'dsn' => '',
              'hostname' => 'localhost',

    'username' => 'root',
    'password' => '',
    'database' => 'mydatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);
add below code for second database in same file.
 $db['second'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mysecond',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Step 2 : Add below code in application/config/autoload.php file
         $autoload['libraries'] = array('database', 'email', 'session');
Step 3:  By default the first database will call if you want to call second database
         in your model please follow below example
   class Seconddb_model extends CI_Model {
        function __construct(){ 
             parent::__construct();
            //load our second db and put in $db2
            $this->db2 = $this->load->database('second', TRUE);
        }
        public function getsecondUsers(){
            $query = $this->db2->get('members');
            return $query->result(); 
        }
  }

29.  












1 comment:

  1. Thanks for sharing such a nice information with us on Code Igniter and MVC. Very useful lines and to the point.Appreciate your skill , keep sharing such wonderful information.
    Code Igniter Interview Questions Answers
    Code Igniter Advanced Interview Questions Answers
    Code Igniter Basic Interview Questions Answers
    Hooks in CodeIgniter

    ReplyDelete