Category Archives: CodeIgniter

Codeigniter Interview Questions answers and tutorials, expert tips and tricks

Codeigniter Download

Codeigniter 4 has been released and can be used for application development. The new version of code igniter is supported with PHP 7.2 or higher. So Latest release of Code Igniter has all those features that other powerful MVCs framework have.

Code igniter 4 Can be downloaded easily from Code igniter Official Website. Below is the link

Download Codeigniter here : https://codeigniter.com/download


Read More about Code igniter:

How to start with Codeigniter

What is New In CodeIgniter 4.x?

 

Spread the love

Code Igniter 4 Release Date

CodeIgniter is an open-source software rapid development web framework, for use in building dynamic web sites with PHP.

Codeigniter is a lightweight MVC architecture based PHP framework.

This is popular for its performance and zero configuration. Codeigniter has beautiful documentation. Since CI is the most flexible PHP MVC framework, people love to work on this.

CodeIgniter is loosely based on the popular model–view–controller (MVC) development pattern. While controller classes are a necessary part of development under CodeIgniter, models and views are optional.

CodeIgniter can be also modified to use the Hierarchical Model View Controller (HMVC) which allows the developers to maintain modular grouping of Controller, Models and View arranged in a sub-directory format.

Till now the biggest release of CodeIgniter is Codeigniter 4.0 or CI 4.0. A final release for the rewritten CodeIgniter 4.0 is live.

The first public version of CodeIgniter was released by EllisLab on February 28, 2006.

Developers all over the world were waiting for its release and on 24 Feb 2020, It was released.

Waiting time is over now the alpha is released by Code Igniter officials finally, last month.

The first stable version of CI 4 is CodeIgniter 4.0.0.

Key Features of Code Igniter 4.x:


  • High Performance MVC framework
  • Minimal Configuration as the earlier versions
  • HMVC Structure
  • Based on PHP 7.2 and ahead
  • An MVC framework with a small footprint
  • Highly secured and inbuilt CSRF protection for HTTP requests

Server Requirements for Code Igniter 4.x



PHP version 7.2 or higher is required, with the following extensions installed:

  • intl
  • libcurl if you plan to use the HTTP\CURLRequest library

Additionally, make sure that the following extensions are enabled in your PHP:

  • json (enabled by default – don’t turn it off)
  • xml (enabled by default – don’t turn it off)
  • mbstring
  • mysqlnd
Spread the love

How to start with Codeigniter

What is Codeigniter?

Codeigniter is a PHP based Web development framework.Code igniter follows MVC and HMVC pattern for application development. This is one of the easiest and the simplest MVC frame work available in PHP. It doesn’t demand any configurational setting before execution. We just need to download the Codeigniter source code and to execute it on webserver.

How to and from where we will find the CodeIgniter?

We can download the latest release source code from official website of CodeIgniter [https://codeigniter.com/download]. It is a 2.7 MB zip file for CodeIgniter 3.1.10.

We can also clone it or fork it from Git Hub [https://github.com/bcit-ci/CodeIgniter].

When we will extract we will find 3 folders

  1. application
  2. system
  3. user_guide

application – is what we will use for creating modules,display and our logic will remain there in Models,Views and Controllers.

system – folder is core files of CodeIgniter, that we don’t need to work on.

user_guide – is the tutorial, documentation and examples of how to use Code igniter and this is the best documentation available for any MVC framework.

How to configure it?

No any configuration required. Just put the extracted folder inside your localhost directory and run it, You will find a welcome home screen.

default-home-page-of-codeigniter
Spread the love

MVC Web Development Framework

What is Web Development Framework?

There is a huge number of server-side scripting languages, using them we can create web applications. Almost the scripts are full-fledged programming language and featured with Object Oriented Programming Systems. Popular of them are Java, PHP, Python, Ruby,Perl. At the early age of web the applications were built on conventional logic and components, are not organized or not reusable. As the next generation, web development technologies came into existence the requirement of frameworks increased.A need for such a tool was very important as they are time and cost efficient.

Now we have many frameworks with huge communities. Frameworks are the collection of basic building blocks and reusable code in an organized manner where maintenance and development both are painless processes. They implement code re-usability, inheritance, security, abstraction, accessibility, integrity, reliability, readability, maintainability in our applications. Now we are able to develop very robust applications in very less time. frameworks are enriched with various libraries and plugin. They also provide flexibility to extend the functionality of the core. Almost the framework is based on Model-View-Controller or MVC development pattern.

What is MVC?

MVC is a software architectural pattern, which provides a modular structure to an application and application is layered into Models(M), Views(V) and Controllers(C).

MODEL

Model is a layer where all the data building logic is present. This layer is abstract from direct access. We write or database queries and fetch and format data in this layer with given parameters. This layer is a central layer of all three.

VIEW

A view is a presentation layer. We see the desired results here in our browser. The user directly communicates with forms and perform actions and submit inputs. This is an end user layer where HTTP response displayed and request triggered by user actions.

CONTROLLER

A controller is an intermediate layer and create a pool between Model the data logic layer and View the representational layer. It collects user actions based on URI and parameters. Routing and reverse routing happen here.

Advantages of MVC Frameworks:

  1. Fast and quick development of complex web-applications.
  2. Collection of Plugins are available for most of the general purpose activities.
  3. Easy maintenance and debugging. Frameworks provide debugger kit , that eases the debugging process.
  4. MVC provides a modular structure to application that is why MVC based applications are flexible and robust.
  5. Most of them provide Database manipulation library, so no need to write custom and complex queries very often.
  6. Inbuilt security and migration features.
  7. Most of them come with a command-line interface to generate code-snippets and modules.
  8. They create SEO friendly URLs to easy for search engines to recognize your application urls.

What are the popular MVC framework based on PHP?

There are numerous MVC framework based on PHP. Some of them are as:
Laravel – Laravel is the most popular PHP framework with the latest release of PHP and suitable for heavy applications.It comes with Inbuilt Authentication and security features. Laravel has a powerful ORM and query builder. Laravel has a unique feature of artisan CLI tool.Blade template engine is used for presentation on view.

Zend Framework

Created by the developers of PHP.Zend Framework is a collection of professional PHP packages with more than 345 million installations. It can be used to develop web applications and services using PHP 5.6+, and provides 100% object-oriented code using a broad spectrum of language features. Zend Framework uses Composer as a package dependency manager; PHP Unit to test all packages; and Travis CI as a Continuous Integration service. Zend Framework also follows PHP-FIG standards and includes an implementation of PHR-7 for HTTP message interfaces (as shepherded by Matthew Weier O’Phinney, Zend Framework project lead).

CakePHP

CakePHP is a Rapid development framework written in PHP 5.6 and having a unique feature of Naming Convention. CakePHP has a powerful tool of bake console. We can create scaffolding within no time. It is suitable for Web services as well as small and heavy applications. We can use a template engine as well for the presentation layer.

Codeigniter

This is a zero-configuration framework and mostly used for small scale application. It comes with all the features of OOPS and security parameters. It is fast ,and the most flexible among others in a group. Code-igniter has wonderful and organized documentation and a huge community over the web. Codeigniter also provide the feature of HMVC and templating.

Yii

Fastest growing over the internet and popular in recent years. Featured with MVC structure and can be used for small as well as heavy applications. It handles complex WSDL services easily.

Phalcon

Phalcon is a secure and well documented MVC framework. It is suitable for any type of applications. It has implemented with very high-security level.

Spread the love

What is New In CodeIgniter 4.x?

As we all know CodeIgniter is a PHP lightweight MVC framework.

It provides us fast, flexible, and secure techniques to develop PHP based applications.

The Codeigniter 4.x alpha and beta are released but the available version is not recommended for production use.

The flexibility of Codeigniter is maintained as usual along with the advancement of compatibility with PHP 7.

 

Core Features of CodeIgniter


  • CI is an MVC framework with a small footprint.
  • Codeigniter gives exceptional performance.
  • This is an MVC  framework with zero configuration.
  • No command-line configuration setup or dependencies installation to start(Optional).
  • CI is not restricted to any naming convention or coding rules.
  • No need to learn about advanced concepts like PEAR.
  • You do not need to learn template engine rendering. 
  • Simple, Clear and easy to understand documentation.

Features of Codeigniter 4.x


  1. The earlier versions of Codeigniter are based on PHP 5.6 or lower but the Codeigniter 4 will be featured with PHP 7.2 functionality and compatibility.
  2. It required the *intl* extension of PHP installed on the server.
  3. If we would like to use CURLRequest, we will need lib curl installed.
  4. Supported databases are:
    1. MySQL (5.1+) via the MySQLi driver
    2. PostgreSQL via the Postgre driver
    3. SqLite3 via the SQLite3 driver
  5. CodeIgniter 4 can also be used with command-line programs. As per the latest trend, most of the frameworks provide CLI usability and library. Since Codeigniter 4.x the framework will also be providing CLI interfaces for different purposes.
  6. The following PHP extensions should be enabled on your server: 
    1. Php-json
    2. Php-mbstring
    3. Php-mysqlnd
    4. Php-xml
  7. If you want to use CURLRequest in your CI application, you will need to install libcurl.
  8. The framework now provides for a public folder, intended as the document root for your app
  9. Hooks in Codeigniter are a great feature in is maintained and improved as well.

How to install Codeigniter 4?



Codeigniter 4 can be installed using many methods

  • In Manual Installation, you need to download the latest release from official site and can place it in your www directory after extracting it.
  • If you want to use the composer tool you need to install the composer first and then you can install using command line. Composer will also help you to add third-party plugins in your project in the future. You can download and install the composer from this link: https://getcomposer.org/
  • You can also clone the git repository of CodeIgniter.

Directory Structure for Codeigniter 4.x



A newly installed application has six directories:

  1. application
  2. system
  3. public
  4. writable
  5. tests
  6. Docs

Application Structure

  1. The framework still has app and system folders, with the same interpretation as before
  2. The framework now provides for a public folder, intended as the document root for your app
  3. There is also a writable folder, to hold cache data, logs, and session data
  4. The application folder looks very similar to that for CI3, with some name changes, and some subfolders moved to the writable folder
  5. There is no longer a nested application/core folder

The application directory i.e. app is the source code of your application. All the stuff done by you will remain here. The default structure of the app directory is as :

/app

        /Config         Stores the configuration files

        /Controllers    Controllers determine the program flow

        /Database       Stores the database migrations and seeds files

        /Filters        Stores filter classes that can run before and after a controller

        /Helpers        Helpers store collections of standalone functions

        /Language       Multiple language support reads the language strings from here

        /Libraries      Useful classes that don’t fit in another category

        /Models         Models the database and business logic.

        /ThirdParty     ThirdParty libraries that can be used in application

        /Views          Views make up the HTML that is displayed to the client.

The above concepts will help you when you will doing any application on code igniter or you will be in CodeIgniter interview.

Spread the love

Hooks in CodeIgniter

In code igniter hooks are the points before and after the execution where we can call some specific functions.

These functions are called hooks and points where we call hooks are called hook points.

Hooks in Codeigniter are useful when we have to make some changes throughout the application, then we can do this without hacking all the files, just adding one hook at the appropriate point.

We can modify the way of usual rendering in code igniter application.

So hooks facilitate modification in functionality without changing the core.

Hooks in Codeigniter is important part of any Codeigniter Interview.

How we can use a hook in the Codeigniter framework?

Before we use any hook in application we need to enable the hook in config.php file. Set the enable_hook config variable: TRUE,

$config['enable_hooks'] = TRUE;

The Codeigniter framework provides the number of Hook Points to ease the development and modification in the application:

[1]pre_system:
The pre_system is called very early during system execution.

Only the benchmark and hooks class have been loaded at this point.

[2]pre_controller:
As per the name just called before any of your controllers being called.

When all the base classes are loaded, routing and security checks are done a pre_controller hook is called.

[3]post_controller_constructor:
The hook is called just after the controller class instantiated but none of the methods is called.

[4]post_controller:
Called immediately after your controller is fully executed.

[5]display_override:
We have the _display() function in our core and we use it to render our view on the browser after the execution of all programs.

display_override allows use to display our own content at desired places.

$this->CI => get_instance();
$this->CI->output->get_output();

[6]cache_override:
We can call our own function instead of _display_cache() function using the cache_override hook. We can define our own cache display mechanism.

[7]post_system:
At the end of the system execution when final rendering is done post_system is called.

Define a hook :
A hook is defined in the hooks.php file located at application/config

Example of define a pre_controller hook:

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

The Hooks in Codeigniter will boost your learning  Codeigniter.

Spread the love

Top 10 Codeigniter Interview Questions and Answers for Experienced

1- What is hook?
CodeIgniter’s Hooks feature modify the core functionalitis of the framework without changing the core files. For example, If you want to run a script right before your controllers get loaded, or right after or at any other location, you can use Hook.
2- How many types of hooks are there in Code Igniter?
There are 7 availabe hook points:
pre_system :
Called very early during system execution. Only the benchmark and hooks class have been loaded at this point. No routing or other processes have happened.
pre_controller :
Called prior to controllers being called. All base classes, routing, and security checks have been done.
post_controller_constructor:
Called after controller is instantiated, but prior to any method calls happening.
post_controller:
Called after the controller is executed.
display_override:
Overrides the _display() method, used to send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to reference the CI superobject with $this->CI->get_instance() and then the finalized data will be available by calling $this->CI->output->get_output().
cache_override:
Enables you to call your own method instead of the _display_cache() method in the Output Library. This permits you to use your own cache display mechanism.
post_system:
Called after the final rendered page is sent to the browser, at the end of system execution after the finalized data is sent to the browser.
Creating a hook :
$my_hook=array(
‘class’ => ‘YourClassname’,
‘function’ => ‘your_function_name’,
'filename' => 'your_filename.php',
‘params’ => array(‘p1’, ‘p2’)
'filepath' => 'hooks',  
            );
$hook[‘pre_controller’] = $my_hook;

3- Can we use multiple call to same hook?
Yes , we can use multiple call to same hook. Then We have to use multidimentional array:
$hook[‘pre_controller’][]= $hook_one;
$hook[‘pre_controller’][]= $hook_two;
4- What are the benifites of using hook in an application?
-We can modify core functionalitis without touching the core files.
-We can generate derired output without changing the view files.
-we can make a hook for recurring calls , like including footer and header in each function, without calling them in each controller function.
-we can create a script to minify the code before excecution take place.
-We can easily implement security checks, privacy, session, cache using hooks and can seperate these implementation from the main functionalitis.
5- WHat is HMVC?
HMVC is a Modular version of MVC. In this system we can implement modules for particular purpose. We may have put out controller , views and model in different modules. All these modules will be available in modules folder in application. HMVC stands for Hierarchical Model View Controller.
6- What is a module?
A module is a part of application and a full featured block which is implemented on HMVC pattern. A module contains its own Model, View and Controller. Although these resources can be shared with other modules.
7- What is difference between Library and Helper?
A CodeIgniter helper is a set of related global functions, you can call them any where in application. Once you load the helper file you can directly call the function. Basically the helper is procedural.
But a Library is a class, which you need to make an instance of the class. Once the library is loaded, we need to use $this operator to call the Library function. This is Object Oriented.
8- What is Routes in Code Igniter Framework?
Routing is the communication between URI and Controller. Routing decides the controller calls and parameters in code igniter. We can overwrite the routing rules in routes.php file.
9- How to use or enable libraries CodeIgniter?
We can initialize the library in controllers as given below:
$this->load->library('my_library_class');
10- Why CodeIgniter is a loosely coupled mvc framework?
CodeIgniter is called a loosely coupled mvc because, it provides unlimited flexibility to developers. It allows us to write and execute our custom codes, library, helpers. We can use call model and controllers functions in views and also can write custom code on views. It works like a core php when some one is going to manipulate it and on the other side it provide a modular structure to our application, XSS and CSRF functionalitis. It provides us lots of inbuilt library and also compatible with many more custome libraries. It never restricts us to write and execute any code.
Spread the love

15 Advance Code Igniter Interview Questions and Answer


How routing is beneficial in Code Igniter?
Routing provides a way to alter your URL and redefine it according to you. It helps in security and SEO. We can create URL having keywords and phrases influential for SEO ranking.What is a helper?
Helpers are the file having functions for specific purposes. We can directly call them in our script.There is numerous type of helper:
  • Array Helper: It has functions that we use to manipulate arrays.
  • File Helper: Use of this helper is to play with files as upload an image.
  • HTML Helper : Html helper is used to compose HTML dom using php code.
  • URL Helper: We use it to create and construct or redirect URLs.
What does autoload.php do?

It loads when the application start loading contains and default parts of application call. It has information to load the segments that we need to load automatically. For example, we may need to load some models automatically.

How can we connect code igniter to our database?
There is a database.php file in the config directory. We can put here our database information like database name, hostname, username and password and It will be connected.

Can we call multiple model function in a single controller function?
Yes, of course. We can call any number of model and their functions in a single controller class?

Can we write database queries in a controller?
Yes, we can write database queries directly in controllers but this is not a good practice. We should write database queries always in the model.

How can we pass data to view?
We create an array having a particular key and pass this array to load view call. We will have this data on the view page as having the name of the key given to data array.

<?php
$data['employee']=array("name"=>"Dhananjay");
$this->load->view("employee_info",$data);
?>

Now on the employee_info.php page, we will have a $employee variable and that will store the data passed in the array $data in the controller.

How can we pass a parameter to controller function?
A parameter can be passed to URL segment after backslash next to function route. Suppose “admin” is a controller , “all_user” is a function and “active” is a parameter. Now we have to pass this to function that it can list the active user so we can call as given below:

<?php echo site_url("admin/all_user/active")?>

What is a library in Code Igniter?
Code Igniter library is a utility to extend the functionality and to use some predefined functions and classes. We have different libraries for different purposes as upload, database etc.

How can we execute a raw query in Code Igniter?
Using query builder library of code igniter we can execute raw query. For example,

db->query($sql);
$result=$query->result_array();
?>

What is URL helper?
We use URL helper to do manipulation with URL. We can easily create custom URL, we can extract parameters from URL, we can easily create custom anchors, form action, and page redirection.

How the database library provide strength to Code Igniter framework?
Database library has query builder functions. It works with single data and also in batch data. It accepts the array and single values as parameters. Functions are very similar to MySQL query phrases and keywords. We can use almost the query using query builder. It fetches the data in all possible formats. We can select, update, join, delete the records in very simple and robust way.

How we will submit data using a form on code igniter view?
We can give the controller function route as the form action. When we will submit this for, the controller function will be called and data will be collected using $_GET or $_POST arrays, as the method defined in the form.

How we create a session variable and how will we get that value stored in a session variable?
Code igniter has session library.It uses four types of the driver to store session data:
1-files
2-database
3-redis
4-Memcached
The file is the default storage.
After loading session library we can use session class and its method to set or get the session value.

<?php 
$this->load->library('session');
//set session data
$this->session->set_userdata('user_session_name', 'session_value');

//check session
$this->session->has_userdata('user_session_name', 'session_value');

//get session data
$this->session->get_userdata('user_session_name', 'session_value');

//destroy session data
$this->session->unset_userdata('user_session_name');
?>

How can we upload any file in Code Igniter application?
Code igniter has upload library. We will use this library and set preferences in $config variable.
After initializing library we use call do_upload() function and it will complete the task.

Spread the love

Code igniter Interview Questions and Answers

What is MVC?
MVC is a three-tier architecture of application development approach.Almost the popular languages use this pattern. MVC provides Modular structure to an application. Three interconnected parts are Model, View, and Controller.
M: Model, that means data handling and information interchange. Implement CRUD.
V: view i.e. front end and representational parts, where user interacts with machine
C: Controller, The business login, handle user request an passes to model and in return provide results to the user.

What is difference b/w MVC and HMVC?
HMVC is a hierarchical MVC, The whole application is modularized in interconnected modules and each module has its own MODEL, VIEW, CONTROLLER. In HMVC a module is a complete package of User Interface, business logic, and data handling. So MVC is discrete whereas HMVC contains MVC at each level.

How we can load a model in CI controller?
We can call load a model in the constructor as given in the following example:

1
2
3
4
//load model $this->load->(‘users_model’,’users’);
//call model
$this->users->add_new_user($data);
?>

We can also assign an alias to ci_model. We can use ‘users’ to call a model rather than calling ‘users_model’.

What is autoload.php in the config?
This is a file where preloaders are defined. Suppose we want to include database library, any model, URL library, sessions etc, then we can assign all these things here.

What helpers do in CI?
Helpers are the simple PHP functions returning some values and we can call them anywhere in our project once we initialized them.

What are the libraries in CI, explain some popular libraries?
The library is the packages which are designed to implement a particular set of functionalities. For example Database. Once we Initialized it, we do any operation on the database.

What are Hooks?
Hooks provide flexibility to CI core. We can modify the core functionality of CI without disturbing core files and use hooks.Learn more about Hooks in CodeIgniter

How we define URL and redirect in CI?
We use URL helper and then we can create redirect links :

1

these functions provide the way to create URL.

How to write a SELECT query in CI model?
We can write a select query in code igniter using the standard conventions of CI as given below:

1
2
3
4
//table name ‘users’ $this->db->select(‘users’);
$query=$this->db->get();
$result=$query->result();
?>

How to call a CI model Controller?
The following example illustrates, how to call a model in code igniter controller:

1
2
3
4
//load model $this->load->(‘users_model’,’users’);
//call model
$this->users->add_new_user($data);
?>

What are the views?
A view is the display part of the application. It renders the results on screen and provides UI.We can assemble views files in directories as well.

How we define controller in CI?
A controller is the backbone of MVC. It creates a connection between model and view.We can define a controller as illustrated:

1
‘BASEPATH’) OR exit(‘No direct script access allowed’);


How controllers and models are different?
Controllers deals with business logic. When user Instruct the machine to do something, controller listens to that response while interaction another side with a model for data. Whereas a model is data handling layer. It saves data to the database and it requests data from the database that further goes to the controller to display on view.

What is the convention to call controller function with a parameter in CI?
We can call a controller function in uri using the a pattern given below. First part of URI is base URL. Base URL followed by controller route and followed by function name , parameters.
base_url/controller_name/controller_function/param1/param2
[Controller Class]/[controller methos]/[parameters]

How to write JOIN Query in Code Igniter?
Code Igniter has a very rich Database library. It provides a flexible way to call and create logics. Either we can use raw queries or we can use join() function.

1
2
3
4
5
6
$this->db->select(‘t1.name,t2.email’);
    $this->db->from(‘table1 as t1’);
    $this->db->join(‘table2 as t2’, ‘t1.id = t2.user_id’, ‘left’);
    $query = $this->db->get();
    return $query->result();
?>

How to apply where clause in Code Igniter?
Using Code Igniter Database library function ‘where()’ we can apply where clause.

1
2
3
4
5
6
7
8
$where=array( ’email’=>me@example.com,
‘status’=>’active’
);
$this->db->select(‘name,email,mobile’);
$this->db->get(‘users’);
$query=$this->db->where($where);
$result=$query->result();
?>

What is routing?
Routing is a way to define URI and how to call controller methods with a particular URI.
Routing provides flexibility to change the way we call controller functions. We can rename controller and functions. This enhances the security features as well as we can create SEO friendly URLs.

What is the way to fetch query results in CI?
Ther are many ways to fetch result in Code Igniter. Some of them are as follows:
result();
result_array();
row();
row_array();
unbuffered_row();

How we call controller method using AJAX?
Simply we can call the URL using proper method and parameters, and then handle those request on a controller and if required we can render a view.

How to define a session variable in CI?
First of all, we need to load session library and then we can call some library functions to accomplish this task:

1
2
3
4
//load library $this->load->library(‘session’);
//define a session variable named ‘user_id’
$this->session->set_userdata(‘user_id’, $user_id);
?>

 

Spread the love