CodeIgniter Tutorial: The Complete Guide

CodeIgniter Tutorial: The Complete Guide

Website development can seem challenging, especially if tackled without any assistance. Luckily, there are development tools like CodeIgniter. It’s a PHP framework maintained by the British Columbia Institute of Technology with a simple yet effective toolkit for developing web applications.

In this CodeIgniter tutorial, we’ll go through the process of installing and setting up the CodeIgniter framework on web hosting and a VPS and demonstrate how to create a simple web application.

Set Up CodeIgniter for Your Website

Before we start, keep in mind that CodeIgniter requires a Linux, Apache, MySQL, and PHP (LAMP) stack. Luckily, it comes pre-installed with Hostinger’s web hosting plans.

However, if you choose a VPS plan, you will need to install the LAMP stack first. Here’s how to install LAMP on Ubuntu or CentOS. When done, proceed with the CodeIgniter setup.

Hostinger web hosting banner

Step 1. Installing CodeIgniter

CodeIgniter can be installed automatically via Composer or manually by using File Manager.

Important! For the Composer method, SSH access is required. Use PuTTY / Powershell on Windows or the built-in terminal shell on Linux and macOS.

Install CodeIgniter 4 Using Composer

  1. Log in to your SSH account and navigate to the public_html root directory with this command:
cd domains/
  1. Install CodeIgniter 4.
composer create-project codeigniter4/appstarter project-root 

The command above will create a project-root directory for the CodeIgniter files. In this tutorial, we’re using the latest stable CodeIgniter version – 4.1.9. You can use the command below from your CodeIgniter directory to update it:

composer update
  1. For convenience, we recommend moving the contents of project-root to the public_html directory. First, determine the current directory with this command:

It will look something like this:


Now move the files:

mv project-root/* /home/u123456789/domains/ 
  1. Once that’s done, enter this URL into the browser:  

Make sure to replace with your domain.

CodeIgniter’s default screen will appear, letting you know it was installed successfully.

Install CodeIgniter 4 Manually

If you want to skip the SSH part needed for Composer, go with the manual installation.

Remember that even though the manual method is simple, you will need to check for merge conflicts when updating your website. Follow these steps to perform the manual installation:

  1. Download the latest version of CodeIgniter.
  2. Using File Manager, extract it in the root directory –
  3. The framework-4.1.9 folder will appear. Open it and double-click the folder within. You should see a window like this one:
A File Manager page showcasing Codeigniter installation files

Press CTRL + A to select all the files and use the Move button to transfer everything to public_html:

All of the CodeIgniter files selected with the red border indicating the move button

The path will look like this:

The File Manager move dialog box
  1. Open the browser and enter this URL:

Make sure to replace with your domain name.

CodeIgniter’s default screen will appear, which means it was installed successfully.

Step 2. Configuring CodeIgniter

After installing CodeIgniter, it’s crucial to configure it so it works correctly. We recommend starting by creating a .htaccess file and pasting this snippet into it:

RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]

These .htaccess rules will make the CodeIgniter website URL look like this: 

Instead of:

After that, proceed with the advanced configuration.

Configuring CodeIgniter for Web Hosting Plans

In this section, we’ll discuss the advanced settings for web hosting plans. Let’s start with a new MySQL database.

  1. Find the HostingManageMySQL Databases section on Hostinger’s hPanel:
The hPanel dashboard with the databases option highlighted
  1. Once there, specify the database name, username, and password and click Create:
Databases management section in the hPanel with a highlight on the create button
  1. Navigate to File Manager and open the Database.php file for editing. Here’s the full path:
  1. Locate the following section of the file and replace the details with the information of your newly-created database – username, password, and database. The rest of the values should follow this example:
public $default = [
'DSN'      => '',
'hostname' => 'localhost',
'username' => 'u123456789_user',
'password' => 'Y0ur$tr0ngPa$$w0rd',
'database' => 'u123456789_name',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug'  => (ENVIRONMENT !== 'production'),
'charset'  => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre'  => '',
'encrypt'  => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port'     => 3306,
  1. Set up your domain name by modifying CodeIgniter’s App.php file found here:
  1. Locate the following line and change its value to your real domain name:
public $baseURL = ''; 

Save the file and exit.

The database is now synced with CodeIgniter.

Configuring Virtual Hosts on VPS

VPS users can run multiple CodeIgniter applications on a single domain name. To do so, they need to set up virtual hosts.

Important! Make sure that your VPS is using Apache and not Nginx or any other web server

  1. Ensure that the document root is synced with the installation directory of CodeIgniter. To do so, open the virtual host file.
sudo nano /etc/apache2/sites-enabled/000-default
  1. Look for the following block:
<VirtualHost *:80>
DocumentRoot /path/to/codeigniter
<VirtualHost *:80><br>
  1. Change /path/to/codeigniter with the actual path of the CodeIgniter installation directory. By doing this, all URLs will point to this folder. Save the changes by pressing CTRL + X and Y.

For a more efficient development process, get rid of index.php from CodeIgniter’s URL format. Here’s how to do it:

  1. Open the config.php file.
nano /public_html/app/Config/App.php

Locate the following line:

public $indexPage = 'index.php';

Replace it with this:

public $indexPage = '';
  1. It’s necessary to re-route future requests by modifying the .htaccess file to ensure that no errors appear. Before doing so, check whether mod_rewrite is enabled.
apache2ctl -M

The above command will output the capabilities of the server. If mod_rewrite is on the list, continue to the next step. Otherwise, execute this line:

a2enmod rewrite

Then, restart Apache.

sudo service apache2 restart 
  1. Create a .htaccess file in the root folder of CodeIgniter.
nano public_html/.htaccess
  1. Paste the following lines to the file. If .htaccess was already created during the configuration part of the tutorial, add all the lines except for the first one. Save the changes and exit the file.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?/$0 [PT,L]<br>
  1. Let Apache know that it should look for the newly-created .htaccess file. To achieve this, open the virtual host file again:
sudo nano /etc/apache2/sites-enabled/000-default

Ensure that AllowOverride is set to All, as shown below:

Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all

After confirming it, save the file.

If done correctly, index.php won’t appear, making the URL look cleaner.

Understanding MVC

Before continuing our CodeIgniter tutorial and learning how to build an application with the framework, we should cover the basics of the model-view-controller (MVC) pattern.

Simply put, MVC is a web development architecture paradigm. It states that the business logic in any application should be separated from the presentation.

  • Model – deals with the database, carries out computations, and more. In short, it is where your business logic is located.
  • View – forms the application’s presentation layer where the data from models is embedded.
  • Controller – will route user requests to the appropriate model. Once the model has done its job, the controller will load the relevant view.

This architectural pattern also gives developers the flexibility to reuse code for multiple views. For example, it will allow you to implement the same navigation bar on every webpage of your application. Moreover, as both views and models are entirely separate, the front-end developers can work in parallel with the back-end team to speed up the development process.

Note that CodeIgniter also subscribes to the Object-Oriented Programming (OOP) paradigm. As such, models and controllers are PHP classes that extend the base classes provided by the framework. Views can also be called PHP files, although the bulk of their content is HTML/CSS. Only a few snippets of core PHP code are present and are used to display the data from models.

Routing Basics

This is how CodeIgniter formats its URL strings:


We have shown you how to remove index.php from the format in the previous section. As a result, your URL will be similar to this example:

Here, welcome is a controller class corresponding to a controller file named welcome.php. This class will call the tester() function and pass ‘1’ as a parameter. More parameters can be supplied similarly, separated by slashes.


CodeIgniter encourages reuse of existing libraries and helper functions to perform common tasks. The framework also lets users decide which library to load and when. This on-demand process results in fast, lightweight, and feature-rich applications.

Loading a library is easy in CodeIgniter. For instance, to load the Database library, pass the following line in your model or controller:


We suggest autoloading common libraries so they’ll be ready whenever needed. CodeIgniter uses the PSR-4 standard, which makes autoloading straightforward:

  1. Open the autoload file:
nano app/Config/Autoload.php
  1. Add the libraries into the psr4 array:
$psr4 = [
'App'         => APPPATH,
'CodeIgniter' => SYSTEMPATH,

Create a Simple App with CodeIgniter

At this point of the CodeIgniter tutorial, you should have a running distribution of CodeIgniter and an understanding of how models, views, and controllers work. Now, we are going to create a simple CodeIgniter web application.

We’ll use the model to fetch agency names from our database and sort and display them using our view. The controller will be used to route the requests between the model and the view.

Once you have a basic knowledge on the fundamental CodeIgniter process, you can start building complete web applications.

Step 1. Creating a phpMyAdmin Table

This section will cover the steps to create a table with phpMyAdmin via hPanel. This table is essential because it will form the basis of our application.

  1. Log in to your hosting account. Navigate to the Databases section and select phpMyAdmin.
  2. Look for the database that you have synced with CodeIgniter and click Enter phpMyAdmin:
phpMyAdmin section on hPanel, red border is indicating a button to enter phpMyAdmin
  1. Once there, select the SQL section, paste in this query, and press Go:
CREATE TABLE agencies (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email Address',
    PRIMARY KEY (id)
    INSERT INTO agencies(id, name, email) VALUES
  (1, 'Development', ''),
  (2, 'Production', ''),
  (3, 'Testing', ''),
  (4, 'Building', ''),
  (5, 'Debugging', '');

It will look like this:

An example query pasted to the phpMyAdmin SQL section. The application will sort out the pasted entries from highest to lowest

This query will automatically create a database filled with the data that we will be able to use later.

Step 2. Creating the Model

Once the database table has been created, begin working on the business logic. To do this, create a model that will retrieve the database values.

  1. Access File Manager
  2. Models are placed in the public_html/app/Models directory so they won’t interfere with application’s directory structure. Go to the Models directory and create a new PHP file called AgencyModel.php.
  3. Paste the following code into the AgencyModel.php file:
<?php namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model; 
class AgencyModel extends Model
    protected $table = 'agencies';
     protected $allowedFields = ['name', 'email'];

As you can see, the model class (AgencyModel) extends the generic Model class that CodeIgniter provides. Note that CodeIgniter requires all class names to begin with a capital letter.

Step 3. Creating the Controller

Next, we’ll create a route using the controller. This way, whenever a user makes a request, the view will be supplied with the information from the model.

  1. To create a new controller, go to the app/Controllers directory and create a file named Agencies.php. Remember, CodeIgniter’s controllers must have the same name as the class inside it.
  2. Paste the following code into the file:
<?php namespace App\Controllers;
use CodeIgniter\Controller;
use App\Models\AgencyModel;

class Agencies extends Controller
  1. We’ll create a simple function to sort all the database entries from highest to lowest. To do so, add this code snippet to the file:
public function index()
  $model = new AgencyModel(); 
  $data['agencies'] = $model->orderBy('id', 'DESC')->findAll();    return view('agencies', $data);
  1. The complete code will look like this:
<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\AgencyModel;

class Agencies extends Controller
public function index()
  $model = new AgencyModel(); 
  $data['agencies'] = $model->orderBy('id', 'DESC')->findAll();    return view('agencies', $data);

Step 4. Creating the View

Finally, we’ll create a view that will display the list of agencies.

  1. Enter the app/Views folder, and create a new file titled agencies.php. The file’s name has to correspond to the view that you told the controller to load, featured in the last line of the view() method.
  2. Paste in the following code and save the file:
<!doctype html>
<html lang="en">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<div class="row mt-3">
     <table class="table table-bordered" id="agencies">       <thead>
          <?php if($agencies): ?>
          <?php foreach($agencies as $agencies1): ?>
             <td><?php echo $agencies1['id']; ?></td>
             <td><?php echo $agencies1['name']; ?></td>
             <td><?php echo $agencies1['email']; ?></td>
         <?php endforeach; ?>
         <?php endif; ?>

The view will display the information passed by the controller in the $data array. The results won’t be stunning since we haven’t added styling to our view. However, you can add inline styling or reference a CSS stylesheet in the view later.

Our sample application is complete. You should be able to run this application by entering the following URL in your browser:

The web application will call the agencies’ controller created in Step 3 and sort the elements of the database.


Learning how to build a web application is necessary if you wish to become a web developer. Luckily, CodeIgniter and its MVC architecture make the development process fast, efficient, and easy for anyone.

In this article, we’ve discussed the essentials of this framework and talked about what makes CodeIgniter so simple yet effective. We’ve also showcased how the MVC software design pattern operates and created a simple application.

If you have any remarks or questions, leave them in the comment section below.

The author

Ignas R.

Ignas takes great satisfaction in helping people tackle even the most complex technical issues. His current goal is to write easy-to-follow articles so that these issues will not happen at all. During his free time, Ignas likes to play video games and fix up things around his house.