CodeIgniter on cloud

1-click AWS Deployment    1-click Azure Deployment

Overview

CodeIgniter is a PHP MVC framework for developing applications rapidly. CodeIgniter provides out of the box libraries for connecting to the database and performing various operations. Like sending emails, uploading files, managing sessions, etc.

For building a web application you spend a lot of time in writing the same code again and again. Frameworks provide you a starting block and minimize the amount of code needed to build a website.

CodeIgniter is PHP driven framework but it’s not a PHP substitute. Diving into CodeIgniter doesn’t mean you are leaving PHP behind. PHP is a server-side scripting language for building dynamic web-based applications.

CodeIgniter contains libraries, simple interface and logical structure to access these libraries, plug-ins, helpers and some other resources which solve the complex functions of PHP more easily maintaining a high performance. It simplifies the PHP code and brings out a fully interactive, dynamic website at a much shorter time. It supports PHP version of 5.2.6 or newer and MySQL version 4.1 or newer. It makes your web more robust and your code easier to read and maintain. It is a free toolkit, light weight and easier to install.

Why you should use CodeIgniter:

  • If you need a framework with small footprint.
  • You need a high performance.
  • Need a framework which requires zero configurations.
  • Need a framework which don’t use command line.
  • Need a framework which doesn’t require adhering to restrictive coding rules.
  • To get a simplified code structure.

CodeIgniter Application Architecture:

The working of Codeigniter Application is mentioned in a simple flowchart given below, which will help you understand the entire process effortlessly in easy steps. Each and every step in the flow chart is explained in elaboration and point wise for your easy grasping.

CodeIgniter App Architecture

    • As shown in the Flow chart, whenever a request comes to CodeIgniter, it will first go to index.php page.
    • In the second step, Routing decides whether to pass the request to step 3 for Caching or to pass the request to step 4 for Security check.
  • If the requested page is already in Caching, then Routing will sanction the request to step 3 and the response will go back to the user.
  • In case the request page does not exist in the Caching, then Routing, will sanction the requested page to step 4 for Security checks.
  • Before passing the request to Application Controller, the Security of the submitted data is checked. After the Security check is done, the Application Controller loads all the necessary Models, Libraries, Helpers, Plugins and Scripts and pass it onto View.
  • The View will provide the page with available data and pass that on for Caching, to process this page quickly for future requests.

Directory Structure of Codeigniter

The Directory structure of the Codeigniter is given below in the Screenshot Image:

CodeIgniter Application Architecture
Further to this the Directory Structure of CodeIgniter is divided into three folders:

  • Application
  • System
  • User_Guide

Application

As indicated in the name the Application folder contains all the code of your application that you are building. This folder is the actual place where we develop the project. Within this application folder there exist several other folders as explained below:

    • Cache – The Cache folder contains all the cached pages of your application. These cached pages would increase the overall speed of accessing the pages.
    • Config – The Config folder contains various files to configure the application. With the help of config.php file, you can configure the application. Using database.php file, you can configure the database of your application.
  • Controllers – This folder contains the controllers of your application. It is the basic part of your application.
  • Core – This folder contains the base class of your application.
  • Helpers – The helper class of your application can be put in this folder.
  • Hooks – With the help of files in this folder you can tap into and modify the inner workings of the framework without hacking the core files.
  • Libraries – This folder contains the files of the library developed for your application.
  • Logs – This folder contains the files related to the log of the system.
  • Language –This folder contains language related files.
  • Models – The database login is placed in this file.
  • Third_Party – The plugins can be placed in this folder for using it in your application.
  • Views – The HTML files of your application can be placed here.

System:

The System folder contains the CodeIgniter core codes, libraries, helpers and other files, which helps make the coding easy. The libraries and helpers are loaded and used for web application development. This folder contains all the CodeIgniter code of consequence again organized into various folders mentioned as below:

    • Core – The Core folder contains CodeIgniter core class. Nothing should be modified here. Since all your work will take place in the application folder, if you intend you extend the CodeIgniter core you will have to do it with hooks, which itself exist in the application folder.
    • Database – This folder contains the database drivers and database utilities.
  • Fonts – This folder contains the font related information and the utilities.
  • Helpers – The standard CodeIgniter helpers such as data, cookie, and URL helpers exist in this folder.
  • Language –Contains language related files. This can be ignored for now.
  • Libraries – The folder contains standard CodeIgniter libraries such as e-mail, calendars, file uploads etc. You can create your own libraries, extend and even replace standard ones. But those will be saved in the application/ libraries directory to keep them separate from the standard CodeIgniter libraries in this particular folder.

User_Guide:

It is the offline version of user guide of CodeIgniter Website. In other words user guide to CodeIgniter. Using this the various functions of libraries, classes and helpers can be learned. It is highly recommended that you go through this user guide before building your first web app using CodeIgniter. Apart from these three folders ( Application, System and User_Guide ) there is one more important file named “ index.php” . In this file you can set the application environment and error level and you can define system and application folder name. We highly recommend you not to edit these settings if you do not have enough knowledge of what you are going to do.

CodeIgniter – MVC Framework

Codeigniter is PHP Framework which is built on the top of the MVC (Model-View-Controller) development pattern. Model-View-Controller is a software approach which separates application logic from presentation. Since the presentation is separate from the PHP scripting here, it permits the web pages to contain minimal scripting.

CodeIgniter MVC Framework

    • Model- The Model consists of the data structures. In a way These typically contains the sets of the functions that helps in retrieving, inserting and updating information in the database.
    • View- The view is the information that is being presented to the user. A view in normal case is a webpage, but in case of Codeigniter, it can be a page fragment like header or footer, or it can be any other type of page like RSS as well as for performing UI.
  • Controller- The controller implements the logical implementation for writing the programme and creating the webpage. The controller serves as an intermediary between the model and the view and any other resources needed to process HTTP request and generate a webpage.

CodeIgniter Installation

Codeigniter installation is a very easy process. For the installation please follow the given below steps:

  • Step 1 : Click at the link to download the Codingniter:https://www.codeigniter.com/download
    • Codeigniter comes in three flavors: CodeIgniter 3 (Current), CodeIgniter 4 (Future) and CodeIgniter 2 (Legacy). For more details follow the link mentioned above.
    • We can also get all the latest scripts with GitHub.
  • Step 2 : Unzip the folder
  • Step 3 :Upload all the files and folders to your server.
  • Step 4 :After following step 3, visit the URL of your server, e.g. www.domain–name.com

On visiting the URL you will see the given below type of screen.

How to create a new CodeIgniter project:

We will use Composer to create a new project. I will be using the PHP built-in server, so it’s not necessary to have extra software such as Apache. In this tutorial, we are using the Windows operating system. Therefore, we have created a Sites folder on drive C. You can use any directory that is suitable for you.

Open the command line/terminal and run the following command

cd C:\Sites

We will now create a CodeIgniter project using Composer. Run the following command

composer create-project CodeIgniter/framework ci-app

HERE,

  • The above command creates a new CodeIgniter project version 3 using the latest stable release i.e., 3.1.9 into a directory ci-app.

When the above command has completed running, you should be able to results similar to the following in the terminal

Run the following command to browse to the newly created project directory ci-app

cd ci-app

Let’s now start the PHP built-in web server

 php -S localhost:3000

HERE,

  • The above command starts the built-in PHP server running on port 3000.

Open the web browser and browse the following URL

http://localhost:3000/

You will get the following page

As you can read from the above web page, the page displayed above is rendered by the view located in application/views/welcome_message.php and the responsible controller is located in application/controllers/Welcome.php

CodeIgniter Routing

For now, our application has only a single URL which is the home page. In this section, we will customize the home section. We will create some new URLs that will respond to the different requests.

Let’s start with the home page route

Open the routes file as indicated by the path below

application/config/routes.php 

You should be able to see the following content

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

HERE,

  • $route[‘default_controller’] = ‘welcome’; defines the default controller that responds to the URI requests
  • $route[‘404_override’] = ”; this route allows you to define a custom route for 404 errors. A 404 error occurs when a page is not found. CodeIgniter has a default handler for the error but you can define your own if you so wish.
  • $route[‘translate_uri_dashes’] = FALSE; this option allows you to translate dashes to underscores. We will talk about this option when we look at how routes work in CodeIgniter.

Let’s now look at the controller method responsible for displaying the home page that we saw when we opened the URL http://localhost:3000/ in the web browser

Open the following file

application/controllers/Welcome.php

You should be able to see the following code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

	public function index()
	{
		$this->load->view('welcome_message');
	}
}

HERE,

  • Defined (‘BASEPATH’) OR exit(‘No direct script access allowed’); protects against directly accessing the controller class without passing through the index.php file. Remember, in MVC paradigm all requests have a single entry point, and for CodeIgniter, its index.php. This code blocks all requests that do not come through index.php
  • class Welcome extends CI_Controller {…} defines a class Welcome that extends the parent class CI_Controller
  • public function index() defines a public function that is called by default when you open the homepage
  • $this->load->view(‘welcome_message’); this line loads the view welcome_message. The file welcome_message is located in the directory application/views/welcome_message.php

So far, we have only explored what comes out of the box with CodeIgniter, let’s now try to make some changes. We will create our home page and replace the default page

Create a new file in application/views/home.php

Add the following code to home.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Hello CodeIgniter!</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css">
        <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
    </head>
    <body>
        <section class="section">
            <div class="container">
                <h1 class="title">
                    CodeIgniter Hello World
                </h1>
            </div>
        </section>
    </body>
</html>

HERE,

The above HTML code loads Burma SSS framework and font from CDN network create a very basic HTML document. It applies very simple CSS rule from Burma CSS framework.

Open the following URL in your browser

http://localhost:3000/

You should be able to see the following

Great, we have just successfully modified the home page. Moving on, let’s define our route. Let’s assume our application also needs to be able to show the about us page.

Create a Route

Open the routes file application/config.routes.php

Add the following route

$route['about-us'] = 'welcome/about_us';

HERE,

  • When a visitor visits the URL /about-us, we are instructing CodeIgniter to look for a controller Welcome and execute the method about_us.

Create a Controller

Let’s now define the controller method about us

Open application/controllers/Welcome.php

Add the following method

        public function about_us(){
            $this->load->view('about_us');
        }

HERE,

  • The above code defines a function about_us and loads a view about_us.

Create a View

Let’s now create the view that we just referenced in the above section

Create a new file about_us.php in application/views/about_us.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>About CodeIgniter!</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css">
        <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
    </head>
    <body>
        <section class="section">
            <div class="container">
                <h1 class="title">
                    About us yap...                
                </h1>
            </div>
        </section>
    </body>
</html>

We are good to go, open the following URL in your web browser

http://localhost:3000/index.php/about-us

You will see the following page

If you are able to see the above page then congratulations, you have successfully created a simple application in CodeIgniter.

CodeIgniter Application’s FOLDER & FILE Structure:

It is very important to understand the file structure in CodeIgniter if you want to develop applications successfully.

The following image shows the file structure in CodeIgniter

Let’s now look at the above files

  • application – this is the directory that will contain your application logic. All of your application code will be contained in this directory
  • system – this folder contains the framework core files. It is not advised to make changes in this directory or put your own application code into this directory.
  • user_guide – this directory contains the user manual for CodeIgniter.
  • vendor – this directory contains composer packages source code. The other files related to this directory are composer.json and composer.lock
  • index.php – this is the entry point into the application.

Let’s now look at the directories in more details

Application subdirectories

As we stated above, this directory contains the application code. In this section, we will look at the internal subdirectories

  • cache – stores cached files
  • config – keeps configuration files
  • controller – all application controllers are defined in this controller
  • core – contains custom core classes that extend system files. For example, if you create a base controller that other controllers should extend, then you would place it in this directory
  • helpers – this directory is used for user-defined helper functions
  • hooks – used for custom hooks
  • language – used to store language files for applications that use more than one language
  • libraries – used to store custom created libraries
  • logs – application log files are kept in this directory
  • models -all application models should be defined in this directory
  • third_party – this is used for custom many packages that you or other developers have created.
  • Views – application views go into this directory

System subdirectories

Let’s now look at system subdirectories. Remember this is where the framework source code resides. Therefore, don’t make any changes to the files in this directory.

  • core – this is like the heart of the framework. All of the core file that makes up the framework are located in here. If you would like to extend the functionality of the core file then you need to create a custom core file in the application directory. After that, you can override or add a new behavior that you wish. You should never make changes directly in here.
  • database – database drivers, cache and other files need for database operations are provided in here.
  • fonts – as the name suggests, this directory contains fonts and information relating to fonts
  • helpers – this directory contains helper functions that come out of the box
  • language – contains language files that are used by the framework
  • libraries – contains the source files for the various libraries that come with CodeIgniter out of the box.

User_guide directory

This file serves as a reference guide for you when you want to understand the CodeIgniter API. You should not upload this directory when deploying your application.

Vendor directory

This directory contains source files for packages that you install via composer. The files in this directory should be left as they are. No changes should be made to them. Unlike the user_guide directory, this directory should be uploaded if you are using composer packages in your application.

Index.php file

This directory contains source files for packages that you install via composer

  • The file structure of CodeIgniter is very important to understand to work effectively with CodeIgniter
  • Core Database, fonts, helpers, language, libraries are important system subdirectories of Application Directory
  • User guide directory serves as a reference guide for you when you want to understand the CodeIgniter API. This is the entry point into the application and no changes should be made to this directory.
  • Vendor directory contains source files for packages that you install via composer. This directory contains source files for packages that you can install via composer

CodeIgniter Routes:

What are Routes?

Routes are responsible for responding to URL requests. Routing matches the URL to the pre-defined routes. If no route match is found then, CodeIgniter throws a page not found an exception.

Routes are defined using the formula

example.com/Controller/Method/Parameter/

HERE,

  • Controller -is mapped to the controller name that should respond to the URL.
  • Method – is mapped to the method in the controller that should respond to the URI request.
  • Parameter – this section is optional.

Let’s now look at a practical example.

Consider the following URL

http://localhost:3000/contacts/edit/1

HERE,

  • The name of the controller responding to the above URL is “contacts”
  • The method in the controller class Contacts is “edit”
  • The edit method accepts a parameter. In the case of our example, the value “1” is passed to the method.

Routes Example

Here is a brief background of what we plan to do:

  • Routing – routing is responsible for responding to URL requests. Routing matches the URL to the pre-defined routes. If not route match is found then CodeIgniter throws a page not found exception.
  • Controllers – routes are linked to controllers. Controllers glue the models and views together. The request for data / business logic from the model and return the results via the views presentation. Once a URL has been matched to a route, it is forwarded to a controller public function that interacts with the data source, business logic and returns the view that displays the results.
  • Views – views are responsible for presentation. A view is usually a combination of HTML, CSS and JavaScript. This is the part is responsible for displaying the web page to the user. Typically, the data displayed is usually retrieved from the database or any other available data sources.

To learn how to implement routers on a real-world project, we will assume that we are creating an application for managing contact details. The following table shows the URLs that will be working with.

S/N URL Route Controller Method
1 / $route[‘default_controller’] Welcome index
2 /contacts $route[‘contacts’] Contacts index
3 /contacts/create $route[‘create’] Contacts create
4 /contacts/edit/id $route[‘edit/:id’] Contacts edit
5 /contacts/update/id $route[‘update/:id’] Contacts update
6 /contacts/delete/id $route[‘delete/:id’] Contacts delete

We will create the routes of our application based on the above table. We have defined the URLs, CodeIgniter route, and mapped them to the respective controller and method names.

Creating URL’s for the Application

Let’s create routes for our tutorial project

Open application/config/routes.php

Modify the routes to match the following

$route['default_controller'] = 'welcome';
$route['contacts'] = 'contacts';
$route['create'] = 'contacts/create';
$route['edit/:id'] = 'contacts/edit';
$route['update/:id'] = 'contacts/update';
$route['delete/:id'] = 'contacts/delete';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

HERE,

  • $route[‘default_controller’] = ‘welcome’; defines the default controller Welcome.
  • $route[‘contacts’] = ‘contacts’; defines a contacts route which calls the index method in the Contacts controller
  • $route[‘create’] = ‘contacts/create’; defines a route create which points to the Contacts controller and calls the create method.
  • $route[‘edit/:id’] = ‘contacts/edit’; defines a route edit which accepts a parameter of id and points to the edit method of Contacts controller
  • $route[‘update/:id’] = ‘contacts/update’; defines a route update which accepts a parameter of id and points to the update method of the Contacts class.
  • $route[‘delete/:id’] = ‘contacts/delete’; defines a route delete which accepts a parameter of id and points to the delete method of the Contacts controller.

The following table shows the respective URLs derived from the above defined routes

S/N Route Corresponding URL
1 $route[‘default_controller’] = ‘welcome’; http://localhost:3000
2 $route[‘contacts’] = ‘contacts’; http://localhost:3000/contacts
3 $route[‘create’] = ‘contacts/create’; http://localhost:3000/contacts/create
4 $route[‘edit/:id’] = ‘contacts/edit’; http://localhost:3000/contacts/edit/1
5 $route[‘update/:id’] = ‘contacts/update’; http://localhost:3000/contacts/update/1
6 $route[‘delete/:id’] = ‘contacts/delete’; http://localhost:3000/contacts/delete/1

Now that we have covered the routes let’s create the Contacts controller that will be responding to the actions specified in the routes.

Create a new file Contacts.php in application/controllers/Contacts.php

Add the following code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Contacts extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    public function index() {
        $this->load->view('header');
        $this->load->view('contacts/index');
        $this->load->view('footer');
    }

    public function create() {
        $this->load->view('header');
        $this->load->view('contacts/create');
        $this->load->view('footer');
    }

    public function edit($id) {
        $this->load->view('header');
        $this->load->view('contacts/edit');
        $this->load->view('footer');
    }

    public function update($id) {
        $this->load->view('header');
        $this->load->view('contacts/update');
        $this->load->view('footer');
    }

    public function delete($id) {
        $this->load->view('header');
        $this->load->view('contacts/delete');
        $this->load->view('footer');
    }
}
  • Class contacts extends CI_Controller {..} defines our controller class and extends the CI_Controller class which comes with CodeIgniter.
  • The methods defined above correspond to the routes we defined and those with parameters like delete accept a parameter of $id
  • Notice the functions load three (3) views. The header and footer are common for all methods. The middle view is very specific to the action, i.e. delete for delete function create a view for creating a function, etc. Another important thing to remember is that the views are loaded from the contacts subdirectory.

Views

We still need to take one more step before we can test our routes in the web browser. Let’s create the corresponding views to the above controller methods.

The following image shows what your application will look like

Create the following files in application/views

  • header.php – this file will contain contacts app menu and the header
  • footer.php – this files will contain the application footer.

Create a new directory of contacts in views application/views/contacts

Create the following files inside

index.php
create.php
edit.php

Your file structure should be as follows

Let’s now update the header.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>CodeIgniter Routes</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css">
        <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
    </head>
    <body>
        <section class="section">
            <div class="container">
                <h1 class="title">CI Contacts v1</h1>
                <h2 class="subtitle">CodeIgniter contacts management app</h2>
                <div class="columns">
                    <div class="column is-one-quarter">
                        <aside class="menu">
                            <p class="menu-label">
                                General
                            </p>
                            <ul class="menu-list">
                                <li><a class="is-active" href="#">Dashboard</a></li>
                                <li><a href="/<?=site_url('contacts/create')?>">New Contact</a></li>
                                <li><a href="/<?=site_url('contacts/edit/1')?>">Edit Contacts</a></li>
                            </ul>
                            <p class="menu-label">
                                Settings
                            </p>
                            <ul class="menu-list">
                                <li><a href="#">SMS</a></li>
                                <li><a href="#">Email</a></li>
                            </ul>
                        </aside>
                    </div>

HERE,

  • The above HTML code loads Burma CSS from a CDN network.

The following is the code for the footer.php

            </div>
            </div>
        </section>
    </body>
</html>

Let’s now add the code for the index.php, edit.php and create.php files for contacts.

index.php
<div class="column">Index content goes here...</div>
edit.php
<div class="column">Edit content goes here...</div>
create.php
<div class="column">Create content goes here...</div>

You can save all the changes that have been made.

Open the following URL in your web browser

http://localhost:3000/contacts/

you can click on the New Contact and Edit Contact links and see what happens.

CodeIgniter Insert Data into Database

In this tutorial, We will understand how to insert data into database using Controller model and view. We will use users table to insert, display, update and delete.

This is users table structure

Table Name : users
user_id int primary key auto_increment
name char(50)
email varchar(100)
mobile bigint

Connecting to a Database

In CodeIgniter, We can connect with database in 2 ways. 1.Automatic Connecting – Automatic Connection can be done using application/config/autoload.php

$autoload['libraries'] = array('database');

2. Manual Connecting – If u want database connection for some specific Controller then u can use Manual Connection. in manual Connection u will have to Create connection for every Controller So it would be better to use Automatic Connection.

$this->load->database();

Creating a Controller

Create a new file under the path Application/controllers/Hello.php Copy the below given code in your controllers.

<?php
class Hello extends CI_Controller 
{
	public function __construct()
	{
	//call CodeIgniter's default Constructor
	parent::__construct();
	
	//load database libray manually
	$this->load->database();
	
	//load Model
	$this->load->model('Hello_Model');
	}

	public function savedata()
	{
		//load registration view form
		$this->load->view('registration');
	
		//Check submit button 
		if($this->input->post('save'))
		{
		//get form's data and store in local varable
		$n=$this->input->post('name');
		$e=$this->input->post('email');
		$m=$this->input->post('mobile');
		
//call saverecords method of Hello_Model and pass variables as parameter
		$this->Hello_Model->saverecords($n,$e,$m);		
		echo "Records Saved Successfully";
		}
	}
}
?>

Creating a View

Create a new file under the path Application/views/registration.php Copy the below given code in your view.

<!DOCTYPE html>
<html>
<head>
<title>Registration form</title>
</head>

<body>
	<form method="post">
		<table width="600" border="1" cellspacing="5" cellpadding="5">
  <tr>
    <td width="230">Enter Your Name </td>
    <td width="329"><input type="text" name="name"/></td>
  </tr>
  <tr>
    <td>Enter Your Email </td>
    <td><input type="text" name="email"/></td>
  </tr>
  <tr>
    <td>Enter Your Mobile </td>
    <td><input type="text" name="mobile"/></td>
  </tr>
  <tr>
    <td colspan="2" align="center"><input type="submit" name="save" value="Save Data"/></td>
  </tr>
</table>

	</form>
</body>
</html>

 

Creating a Model

Create a new file under the path Application/models/Hello_Model.php Copy the below given code in your model.

<?php
class Hello_Model extends CI_Model 
{
	function saverecords($name,$email,$mobile)
	{
	$query="insert into users values('','$name','$email','$mobile')";
	$this->db->query($query);
	}
}

Calling/run Hello Controller’s savedata method

Open your web browser and Pass : http://localhost/CodeIgniter/index.php/Hello/savedata

Output : View Pageinsert database in codeigniter
Output : Database
Codeigniter display data from database:

 

Here, we will understand how to display(fetch) data from database and display records in view. In the Previous example we saved records inside users table.In this example We will use users table to display records.

Controller

Copy the below given code in your controllers.

<?php
class Hello extends CI_Controller 
{
	public function __construct()
	{
	parent::__construct();
	$this->load->database();
	$this->load->helper('url');
	$this->load->model('Hello_Model');
	}

	public function savedata()
	{
		$this->load->view('registration');
		if($this->input->post('save'))
		{
		$n=$this->input->post('name');
		$e=$this->input->post('email');
		$m=$this->input->post('mobile');
		$this->Hello_Model->saverecords($n,$e,$m);		
		redirect("Hello/dispdata");  
		}
	}
	
	public function dispdata()
	{
	$result['data']=$this->Hello_Model->displayrecords();
	$this->load->view('display_records',$result);
	}
}
?>

View

Copy the below given code in your view.

<!DOCTYPE html>
<html>
<head>
<title>Display Records</title>
</head>

<body>
<table width="600" border="1" cellspacing="5" cellpadding="5">
  <tr style="background:#CCC">
    <th>Sr No</th>
    <th>Name</th>
    <th>Email</th>
    <th>Mobile</th>
  </tr>
  <?php
  $i=1;
  foreach($data as $row)
  {
  echo "<tr>";
  echo "<td>".$i."</td>";
  echo "<td>".$row->name."</td>";
  echo "<td>".$row->email."</td>";
  echo "<td>".$row->mobile."</td>";
  echo "</tr>";
  $i++;
  }
   ?>
</table>

</body>
</html>

Model

Copy the below given code in your model.

<?php
class Hello_Model extends CI_Model 
{
	function saverecords($name,$email,$mobile)
	{
	$query="insert into users values('','$name','$email','$mobile')";
	$this->db->query($query);
	}
	
	function displayrecords()
	{
	$query=$this->db->query("select * from users");
	return $query->result();
	}
}

Calling/run Hello Controller’s dispdata method

Open your web browser and Pass : http://localhost/CodeIgniter/index.php/Hello/dispdata

Codeigniter delete database record:

Now,we will understand how to delete data from database. We will use users table to delete records.

Controller

Copy the below given code in your controllers.

<?php
class Hello extends CI_Controller 
{
	public function __construct()
	{
	parent::__construct();
	$this->load->database();
	$this->load->helper('url');
	$this->load->model('Hello_Model');
	}

	public function savedata()
	{
		$this->load->view('registration');
		if($this->input->post('save'))
		{
		$n=$this->input->post('name');
		$e=$this->input->post('email');
		$m=$this->input->post('mobile');
		$this->Hello_Model->saverecords($n,$e,$m);		
		redirect("Hello/dispdata");  
		}
	}
	
	public function dispdata()
	{
	$result['data']=$this->Hello_Model->displayrecords();
	$this->load->view('display_records',$result);
	}
	
	public function deletedata()
	{
	$id=$this->input->get('id');
	$this->Hello_Model->deleterecords($id);
	redirect("Hello/dispdata");
	}
}
?>

View

Copy the below given code in your view.

<!DOCTYPE html>
<html>
<head>
<title>Display Records</title>
</head>

<body>
<table width="600" border="1" cellspacing="5" cellpadding="5">
  <tr style="background:#CCC">
    <th>Sr No</th>
    <th>Name</th>
    <th>Email</th>
    <th>Mobile</th>
	<th>Delete</th>
  </tr>
  <?php
  $i=1;
  foreach($data as $row)
  {
  echo "<tr>";
  echo "<td>".$i."</td>";
  echo "<td>".$row->name."</td>";
  echo "<td>".$row->email."</td>";
  echo "<td>".$row->mobile."</td>";
  echo "<td><a href='deletedata?id=".$row->user_id."'>Delete</a></td>";
  echo "</tr>";
  $i++;
  }
   ?>
</table>
</body>
</html>

Model

Copy the below given code in your model.

<?php
class Hello_Model extends CI_Model 
{
	function saverecords($name,$email,$mobile)
	{
	$query="insert into users values('','$name','$email','$mobile')";
	$this->db->query($query);
	}
	
	function displayrecords()
	{
	$query=$this->db->query("select * from users");
	return $query->result();
	}
	
	function deleterecords($id)
	{
	$this->db->query("delete  from users where user_id='".$id."'");
	}	
}
?>

Calling/run Hello Controller’s dispdata method

Open your web browser and Pass : http://localhost/CodeIgniter/index.php/Hello/dispdata

Output

Pagination in Codeigniter with Step by Step Example:

Databases are living entities. They grow as time passes by. When designing applications, we need to take into consideration the many records that the users will have to browse through. Pagination allows us to break down our results into small manageable parts. The following image shows an example of pagination on Google search.

Here you are going to learn how to paginate database results in CodeIgniter using the pagination library.

Database configuration

We will start with creating the database and inserting some dummy records in it. It will be a single table database with 50 records on it.

Run the following script against MySQL to create the database authors table. Insert 50 dummy records.

CREATE SCHEMA ci_pagination;

DROP TABLE IF EXISTS `authors`;

CREATE TABLE `authors` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `birthdate` date NOT NULL,
  `added` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (1, 'Brielle', 'O\'Hara', 'alexandre67@example.com
	', '1974-05-21', '1999-09-17 19:17:28');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (2, 'Flavio', 'Lehner', 'mafalda85@example.net', '1971-10-14', '1998-09-09 00:25:06');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (3, 'Elmira', 'Johns', 'wellington52@example.org', '1983-11-28', '2015-02-07 15:56:43');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (4, 'Elza', 'Mitchell', 'marisol46@example.org', '1989-03-08', '1992-08-21 00:21:39');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (5, 'Viva', 'Greenfelder', 'era94@example.com', '1995-04-17', '2017-04-30 05:55:39');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (6, 'Maxwell', 'VonRueden', 'mcassin@example.net', '1994-07-01', '1996-05-08 23:30:14');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (7, 'Deontae', 'Becker', 'rory.kub@example.org', '1992-02-19', '2017-07-22 11:49:15');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (8, 'Sylvester', 'Christiansen', 'erohan@example.org', '1990-09-03', '2004-05-08 08:15:37');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (9, 'Torrey', 'Strosin', 'adams.luciano@example.net', '1999-10-09', '2009-08-30 21:30:44');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (10, 'Kelli', 'Smitham', 'daniel.catalina@example.com', '2012-11-07', '1986-01-22 20:52:57');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (11, 'Abigale', 'Schuppe', 'andreanne.hayes@example.net', '2018-02-18', '1994-05-07 06:26:36');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (12, 'Letha', 'Gleason', 'eldridge.heaney@example.net', '2009-02-06', '1998-05-25 04:37:54');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (13, 'Sienna', 'Upton', 'monique57@example.org', '2017-08-17', '2009-08-08 19:08:10');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (14, 'Harley', 'Gutkowski', 'breilly@example.net', '1987-11-30', '1998-07-31 11:08:01');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (15, 'Lois', 'Bednar', 'hpouros@example.net', '2002-02-11', '2001-07-26 15:04:16');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (16, 'Gail', 'McDermott', 'reina.kerluke@example.com', '1987-03-30', '2004-12-15 20:38:29');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (17, 'Sydney', 'Strosin', 'dweber@example.net', '1985-04-29', '2010-08-07 08:50:35');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (18, 'Anne', 'Cremin', 'fritz.schmitt@example.com', '1976-02-15', '1980-03-25 05:29:41');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (19, 'Norberto', 'Bergnaum', 'franecki.javon@example.net', '1971-03-11', '1993-03-20 23:36:25');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (20, 'Arvid', 'Johns', 'pschultz@example.org', '2016-01-03', '1995-04-30 17:07:15');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (21, 'Bernita', 'Fay', 'arne96@example.org', '1983-12-26', '1987-02-23 16:55:28');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (22, 'Gonzalo', 'Gorczany', 'velma.huels@example.com', '1987-10-19', '2016-10-18 19:25:46');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (23, 'Jackie', 'Klein', 'gretchen.howe@example.com', '1971-01-20', '2010-11-16 02:58:05');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (24, 'Andrew', 'Kessler', 'collins.faye@example.org', '1984-08-07', '1971-12-15 08:46:42');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (25, 'Claire', 'Hudson', 'madalyn.wunsch@example.org', '1984-12-19', '1991-07-04 14:35:53');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (26, 'Prudence', 'Runte', 'koch.laurie@example.net', '2008-12-27', '1985-09-30 04:57:55');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (27, 'Destinee', 'Romaguera', 'tromp.tiffany@example.com', '1978-11-09', '1997-11-09 19:58:08');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (28, 'Marianna', 'Harvey', 'clovis.schuppe@example.com', '2013-08-28', '1990-08-06 19:29:19');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (29, 'Eloy', 'Lakin', 'wmorissette@example.net', '1989-12-08', '1974-03-16 03:21:16');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (30, 'Rubie', 'McClure', 'haley.louisa@example.net', '1987-09-12', '1998-07-02 10:45:36');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (31, 'Marisa', 'Stracke', 'zachary76@example.org', '1975-05-28', '1975-03-19 00:57:35');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (32, 'Jacey', 'Beatty', 'dahlia.hermann@example.org', '1979-12-17', '1971-01-21 16:50:58');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (33, 'Idella', 'Ruecker', 'elda.reichert@example.com', '2009-09-15', '1996-04-19 22:27:31');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (34, 'Dimitri', 'Bednar', 'freida.parker@example.org', '1998-12-02', '2008-12-30 23:29:57');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (35, 'Elfrieda', 'Smitham', 'padberg.rex@example.org', '2018-07-23', '1972-04-01 07:52:25');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (36, 'Dwight', 'Walter', 'gmosciski@example.org', '2016-08-15', '1994-07-02 11:06:55');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (37, 'Macie', 'Fay', 'uschuppe@example.net', '1976-01-29', '2005-12-13 18:44:46');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (38, 'Lori', 'Kshlerin', 'mhansen@example.net', '1983-04-08', '1986-01-18 16:03:52');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (39, 'Jeffry', 'Paucek', 'alisha35@example.net', '2002-10-02', '2004-03-29 07:06:03');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (40, 'Yvonne', 'Bernhard', 'jaqueline21@example.net', '2017-11-04', '1986-12-15 23:55:23');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (41, 'Ludwig', 'Heathcote', 'marcelino.kirlin@example.org', '1981-02-09', '2000-08-02 20:45:48');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (42, 'Jadyn', 'Wiegand', 'georgianna.swift@example.net', '1982-06-16', '1980-12-05 13:09:37');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (43, 'Ferne', 'Smitham', 'melany22@example.com', '1996-12-17', '1984-11-18 19:26:27');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (44, 'Meta', 'Corkery', 'xharber@example.com', '1972-03-31', '2007-01-20 00:07:31');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (45, 'Toni', 'Wolf', 'wyman.crystal@example.org', '2012-04-15', '1973-06-22 12:14:37');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (46, 'Zack', 'Luettgen', 'deion.konopelski@example.org', '2003-05-29', '2018-11-19 05:03:21');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (47, 'Kameron', 'Dietrich', 'ronaldo.torphy@example.com', '1973-05-20', '1974-09-16 20:27:17');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (48, 'Zetta', 'Lebsack', 'timmothy.vandervort@example.com', '1996-11-04', '2001-03-06 01:33:01');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (49, 'Benny', 'Hane', 'leone.lueilwitz@example.net', '2008-02-02', '2006-01-27 22:12:39');
INSERT INTO `authors` (`id`, `first_name`, `last_name`, `email`, `birthdate`, `added`) VALUES (50, 'Evans', 'Gleason', 'ccummerata@example.org', '1999-09-09', '1990-09-26 17:50:11');

Now that we have created our database successfully and inserted dummy records in it, let’s configure our CodeIgniter application to communicate with the database.

Open application/config/database.php

Set the database connection parameters similar to the following

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => 'melody',
	'database' => 'ci_pagination',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'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
);

HERE,

  • ‘hostname’ => ‘localhost’, sets the host name of the database
  • ‘username’ => ‘root’, specifies the database name
  • ‘password’ => ‘openseseme’, sets the database password
  • ‘database’ => ‘ci_pagination’, specifies the database name.

We will also be autoloading the database library when our application starts. Let’s do that. Open application/config/autoload.php

Load the database library as shown by the code below

$autoload['libraries'] = array('database');

That’s it for the database configuration.

Let’s now work on the database model for pagination

CodeIgniter Pagination Database Model

Create a new model Authors_model in application/models

Add the following code

<?php

class Authors_model extends CI_Model {

    protected $table = 'authors';

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

    public function get_count() {
        return $this->db->count_all($this->table);
    }

    public function get_authors($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->get($this->table);

        return $query->result();
    }
}

HERE,

  • protected $table = ‘authors’; define a protected variable that defines the database table name for the model
  • public function __construct() {…} calls the parent constructor method
  • public function get_count() {…} returns the total records in the database table. This is a need for pagination purposes
  • public function get_authors($limit, $start) {…} defines a method that will be used to retrieve paginated results from the database. We will be passing in the limit and the start point. The limit defines the total number of records to be returned while start defines the number of records that should be skipped

that’s it for our database model. Let’s now create the routes that will be responding to our paginated results.

CodeIgniter Pagination Routes

Open the routes file in application/config/routes.php

Add the following route

$route['authors/(:num)'] = 'authors';

HERE,

  • We define a route author that accepts an optional parameter of the number. The optional parameter is defined by using the opening and closing brackets. The defined route calls the index method in the Authors controller.

Let’s now move on to the controller for our paginated results

CodeIgniter Pagination Controller

Create a new file Authors.php in application/controllers directory

Add the following code

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Authors extends CI_Controller {

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

        $this->load->helper('url');
        $this->load->model('authors_model');
        $this->load->library("pagination");
    }

    public function index() {
        $config = array();
        $config["base_url"] = base_url() . "authors";
        $config["total_rows"] = $this->authors_model->get_count();
        $config["per_page"] = 10;
        $config["uri_segment"] = 2;

        $this->pagination->initialize($config);

        $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;

        $data["links"] = $this->pagination->create_links();

        $data['authors'] = $this->authors_model->get_authors($config["per_page"], $page);

        $this->load->view('authors/index', $data);
    }
}

HERE,

  • class Authors extends CI_Controller {…} we define a class Authors that extends the CI_Controller class
  • public function __construct() {…} this method initializes the parent constructor and loads the url helper, authors model and the pagination library.
  • public function index() {…} defines the method that responds to our route authors
    • $config[“base_url”] = base_url() . “authors”; sets the pagination URL that will be used to generate pagination links
    • $config[“total_rows”] = $this->authors_model->get_count(); sets the total row that need to be paginated. The value is retrieved from the authors model by calling the get_count method.
    • $config[“per_page”] = 10; defines the rows that need to be displayed per page
    • $config[“uri_segment”] = 2; specifies the URL segment that contains the value that will be used to skip records
    • $this->pagination->initialize($config); initializes the pagination library using the config array value that we defined and assign the above values to.
    • $page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0; checks if the skip number has been set in the second segment of the URI and if its not set then the value 0 is assigned to the variable $page
    • $data[“links”] = $this->pagination->create_links(); creates the pagination links and assigns them to the links key of the $data array variable.
    • data[‘authors’] = $this->authors_model->get_authors($config[“per_page”], $page); retrieved the paginated authors records and assigns them to the authors key of the $data array variable
    • $this->load->view(‘authors/index’, $data); loads the index view in the authors directory and passes in the array variable $data.

That’s it for our model. Let’s now create the view that will display our database results.

Create a new directory authors in application/views

Create a new file index.php in application/views/authors/index.php

Add the following code

<!DOCTYPE html>
<html>
    <head>
        <title>CodeIgniter Pagination</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css">
    </head>
    <body>
        <div class="container">
            <h3 class="title is-3">CodeIgniter Database Pagination</h3>
            <div class="column">
                <table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Contact Name</th>
                            <th>Contact Number</th>
                            <th>Email</th>
                            <th>City</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($authors as $author): ?>
                            <tr>
                                <td><?= $author->id ?></td>
                                <td><?= $author->first_name ?></td>
                                <td><?= $author->last_name ?></td>
                                <td><?= $author->email ?></td>
                                <td><?= $author->birthdate ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <p><?php echo $links; ?></p>
            </div>
        </div>
    </body>
</html>

HERE,

  • <?php foreach ($authors as $author): ?> loops through the results of the $authors variable and prints the results in table
  • <p><?php echo $links; ?></p> prints the pagination links at the bottom of our table.

Let’s now start our application and see the results

In this tutorial, we are using the built-in PHP web server, but you can use any web server that supports PHP.

Open the terminal

Run the following command

cd C:\Sites\ci-app
php -S localhost:3000

HERE,

  • The above command browses to the application code directory and starts the built-in server on port 3000.

Note: the application path has to match the path where you downloaded CodeIgniter. For that, you can use any port number that is free on your computer. It’s not necessary to use port 3000.

Open the web browser and load the following URL

http://localhost:3000/authors

You should be able to get results similar to the following

CodeIgniter has a built-in email library that we can work with when sending emails.

CodeIgniter Email Configuration

We need to have a central place where we can manage the email settings. CodeIgniter does not come with a config file for emails so we will have to create one ourselves.

Create a file email.php in the directory application/config

Add the following code to email.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

$config = array(
    'protocol' => 'smtp', // 'mail', 'sendmail', or 'smtp'
    'smtp_host' => 'smtp.example.com', 
    'smtp_port' => 465,
    'smtp_user' => 'no-reply@example.com
	',
    'smtp_pass' => '12345!',
    'smtp_crypto' => 'ssl', //can be 'ssl' or 'tls' for example
    'mailtype' => 'text', //plaintext 'text' mails or 'html'
    'smtp_timeout' => '4', //in seconds
    'charset' => 'iso-8859-1',
    'wordwrap' => TRUE
);

HERE,

  • ‘protocol’ => ‘smtp’, specifies the protocol that you want to use when sending email. This could be Gmail smtp settings or smtp settings from your host
  • ‘smtp_host’ => ‘smtp.example.com’,specifies the smtp host. For example, if you want to use Gmail then you would have something like smtp.gmail.com
  • ‘smtp_port’ => 465, an open port on the specified smtp host that has been configured for smtp mail
  • ‘smtp_user’ => ‘no-reply@example.com‘, the email address that will be used as the sender when sending emails. This should be a valid email address that exists on the server
  • ‘smtp_pass’ => ‘12345!’, the password to the specified smtp user email
  • ‘smtp_crypto’ => ‘ssl’, specifies the encryption method to be used i.e. ssl, tls etc.
  • ’email type’ => ‘text’, sets the mail type to be used. This can be either plain text or HTML depending on your needs.
  • ‘smtp_timeout’ => ‘4’, specifies the time in seconds that should elapse when trying to connect to the host before a timeout exception is thrown.
  • ‘charset’ => ‘iso-8859-1’, defines the character set to be used when sending emails.
  • ‘wordwrap’ => TRUE is set to TRUE then word-wrap is enabled. If it is set to FALSE, then word-wrap is not enabled

Note: for sending emails to work, you should provide valid configuration parameters. Dummy parameters will not be able to send emails.

CodeIgniter Email View

In this section, we will create the view that will send the email to the recipient.

Create a new directory email in application/views

Create a new file contact.php application/views/email

Add the following code to application/views/email/contact.php

<!DOCTYPE html>
<html>
    <head>
        <title>CodeIgniter Send Email</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>
            <h3>Use the form below to send email</h3>
            <form method="post" action="<?=base_url('email')?>" enctype="multipart/form-data">
                <input type="email" id="to" name="to" placeholder="Receiver Email">
                <br><br>
                <input type="text" id="subject" name="subject" placeholder="Subject">
                <br><br>
                <textarea rows="6" id="message" name="message" placeholder="Type your message here"></textarea>
                <br><br>
                <input type="submit" value="Send Email" />
            </form>
        </div>
    </body>
</html>

HERE,

  • We have a basic HTML form that accepts the email, subject and message then passes the parameters to email route.

CodeIgniter Email Controller

Let’s now create the controller that will be handling sending email.Create a new file EmailController.php in application/controllers/EmailController.php

Add the following code to EmailController.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class EmailController extends CI_Controller {

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

        $this->load->helper('url');
    }

    public function index() {
        $this->load->view('email/contact');
    }

    function send() {
        $this->load->config('email');
        $this->load->library('email');
        
        $from = $this->config->item('smtp_user');
        $to = $this->input->post('to');
        $subject = $this->input->post('subject');
        $message = $this->input->post('message');

        $this->email->set_newline("\r\n");
        $this->email->from($from);
        $this->email->to($to);
        $this->email->subject($subject);
        $this->email->message($message);

        if ($this->email->send()) {
            echo 'Your Email has successfully been sent.';
        } else {
            show_error($this->email->print_debugger());
        }
    }
}

HERE,

  • class EmailController extends CI_Controller {…} defines our email controller that expands the parent CodeIgniter controller.
  • public function __construct() {…} defines the child constructor that calls the parent constructor method.
  • public function index() {…} defines the index method that displays the contact form
  • function send() {…} defines the method that sends the email
    • $this->load->config(’email’); loads the email configuration settings
    • $this->load->library(’email’); loads the email library
    • $from = $this->config->item(‘smtp_user’); gets the sender id from the email configuration file that we defined.
    • $to = $this->input->post(‘to’); gets the to value from the submitted form
    • $subject = $this->input->post(‘subject’); sets the email subjected from the form
    • $message = $this->input->post(‘message’); sets the email message from the form
    • $this->email->set_newline(“\r\n”); defines the new line characters for emails
    • $this->email->from($from); sets the sender email address
    • $this->email->to($to); sets the recipient email address
    • $this->email->subject($subject); sets the email subject
    • $this->email->message($message); sets the email message
    • if ($this->email->send()) {…} attempts to send the email. If the email is sent successfully, then the message Your Email has successfully been sent else debug information is printed on what might have gone wrong.

Let’s now define the email routes

Email Routes

Add the following routes to application/config/routes.php

$route['send-email'] = 'email controller';
$route['email'] = 'email controller/send';

We can now load the contacts form in the web browser

Let’s start the built-in PHP server

Open the terminal/command line and browse to the root of your application. In my case, the root is located in drive C:\Sites\ci-app

cd C:\Sites\ci-app

start the server using the following command

php -S localhost:3000

Load the following URL in your web browser

http://localhost:3000/send-email

You should be able to see the following form

Enter the recipient email, subject, and email message then click on Send Email. If your email configurations are set properly, then you should be able to see the successful message.

Advantages & disadvantages of CodeIgniter PHP Framework:

Comparison:Some frameworks force you to do things by the books but CI lets you use MVC in a way that makes sense you.

CodeIgniter is quicker than cake php, zend, symphony.

Flexibile, Secure & User Friendly

Light Weight, OpenSource and Fast
CodeIgniter has rich set of libraries which are easy to write and change it’s behaviour.

CodeIgniter has logical structure to access these libraries.

Additional libraries are loaded dynamically upon request, based on your
needs for a given process, so the base system is very lean and quite
fast.

CodeIgniter comes with full-range of libraries that enable the most commonly needed web development tasks, like accessing a database, sending email, validating form data, maintaining sessions, manipulating images,

It does not require you to use the command line.

No need to learn templating language as template parser is optionally available.

No need to use any unix commands.. just install tools and uploads to server directory

CI also lets you manipulate your database like add/remove columns from
tables, create new tables and remove old ones using it’s new
database forge library.

CodeIgniter has standard Error Handellin technique

CodeIgniter keeps site secure from CSRF/XSRF Attacks and SQL injection by using built in classes and libraries.

CodeIgniter has Cache library

Uses M-V-C

Though it encourages MVC, but does not force it on you.

CodeIgniter uses the Model-View-Controller approach, which allows great separation between logic and presentation.

Separation of code has been very easy in Codeigniter.

Generates Clean URLs

The URLs generated by CodeIgniter are clean and search-engine friendly.

CodeIgniter uses a segment-based approach Rather than using the standard “query string” approach to URLs.

Extensible

The system can be easily extended through the use of your own libraries, helpers, or through class extensions.

CodeIgniter

assists the developer to build core libraries for the system and
enables you to integrate your own existing scripts with database.

And to improve your productivity it also supports for third-party addons/plugins for additional functionality.

Built in security tools

  • Unsetting all global variables regardless of PHPs register_globals directive
  • Turning off the magic_quotes_runtime directive during system initialization
  • Enable cookie encryption
  • Handelling session data with a database
  • Auto escaping SQL Queries

Configuration and Customizable

This aspect helps the developers to create what they need to develop based on the web applications.In addition, configuration and customizable of the files are easy in this frameworks.

Drawbacks:

Its PHP based only and not very object-oriented in some parts.

Framework itself has no built-in ORM (only via 3rd party solutions). –

CodeIgniter 2.1.3 needs PHP 5.1.6, but versions before 2 still worked with PHP 4.

This was a drag since everybody moved on to use PHP 5.

-CodeIgniter is a powerful PHP framework with a very small footprint, built for PHP coders who need a simple and elegant toolkit t o create full-featured web applications. If you’re a developer who lives in the real world of shared hosting accounts and clients with deadlines, and if you’re tired of ponderously large and thoroughly undocumented frameworks

CodeIgniter is right for you if…

  • You want a framework with a small footprint.
  • You need exceptional performance.
  • You need broad compatibility with standard hosting accounts that run a variety of PHP versions and configurations.
  • You want a framework that requires nearly zero configuration.
  • You want a framework that does not require you to use the command line.
  • You want a framework that does not require you to adhere to restrictive coding rules.
  • You are not interested in large-scale monolithic libraries like PEAR.
  • You do not want to be forced to learn a templating language (although a template parser is optionally available if you desire one).
  • You eschew complexity, favoring simple solutions.
  • You need clear, thorough documentation.

 

Features

CodeIgniter Features:

Let’s see some of the features that make CodeIgniter great. The following list is not exhaustive but gives you an idea of what to expect when working with CodeIgniter.

Small footprint

The entire source code for CodeIgniter framework is close to 2MB. This makes it easy to master CodeIgniter and how it works. It also simplifies deploying and updating it.

Blazing fast

Users tend to favor applications that load very fast. If you have worked with some of the modern frameworks, then you will realize that they take less than one second to load just after installation. CodeIgniter, you can loads on average around less than 50ms. The extra time spent optimizing like is the case in another framework is freed up when you are working with CodeIgniter.

Loosely coupled

The built-in features are designed to work independently without relying too much on other components. This makes it easy to maintain and make upgrades

MVC Architecture

The framework uses the Model-View-Controller architectural design. It is industry standard practices when working with web applications. MVC separates the data, business logic, and presentation.

Excellent documentation:

The framework is well documented, and there are good books, tutorials and answered forum questions on CodeIgniter. This means whatever challenge that you have, chances are someone has already encountered the problem, solved it and the solution is out there for you.

Application specific built-in components:

CodeIgniter has components for sending email, database management, session management and many more as you will discover as we continue with the tutorials.

Extendable:

CodeIgniter comes with some libraries, and helpers out of the box. If what you want is not there or you would like to implement an existing feature your way. Then you can do so easily by creating your libraries, helpers, packages, etc.

Short learning curve:

CodeIgniter is easy to master for anyone who is already familiar with PHP. Within a very short time, the student can start developing professional applications using CodeIgniter.

Leaner Server Requirements:

CodeIgniter does not have many server requirements. This framework is capable of working with PHP4 and PHP5 too. Better still, the Model View Controller (MVC) model that CodeIgniter is built upon makes code separation clear and easy to understand. Through the MVC route that CodeIgniter takes, it becomes very easy to construct and manage large apps.

Easier Installation:

CodeIgniter is plain vanilla yet very simple to use and expand on. With CodeIgniter, you can easily bring variations such as writing new libraries. This versatile framework makes installation very easy, which is really brilliant since installing frameworks in this category can be incredibly challenging indeed. What’s more, CodeIgniter comes with built-in libraries such as zip-encoding, email, sessions uploading, unit testing, and much more. You can also come up with your own helpers and libraries.

Easier Database Tweaking:

With CodeIgniter, you also get database extraction, which means that you can easily create, insert, update, and delete statements, without the need to write out raw SQL. Also, you can easily tweak your database to add or even remove columns, while creating old ones and removing old ones through the CodeIgniter database forge library.

Built-in security tools:

CodeIgniter also comes with several built-in security tools. It also allows you to choose the security level you need. There are default actions that switch off runtime directives while the system initialization can be enabled. At the same time, you can also enable cookie encryption and even handling session data while utilizing a database.

Large user community:

One of the best things about CodeIgniter is that it has active as well as a continuously expanding user community. There is access to a wiki as well as a forum. Moreover, one of the major benefits of CodeIgniter is that it has a very sophisticated yet easily understandable documentation.

Sophisticated Error Handling Function:

What’s more, CodeIgniter comes along with a sophisticated error handling function which has a simple user-friendly interface that helps you to go ahead and detect error functions on a global basis. As part of this approach, you get to detect all PHP errors in your web application without missing inadequacy.

Form Validation Capability:

CodeIgniter comes along with a form validation that you can use to write code in a single line through its effective validation framework system. You can generate errorless codes to ensure various control structures within the HTML form. With this framework, you can even manage database schema updates from one server to another by using the migration aspect, which is painless and hassle-free in CodeIgniter.

-Major Features of  CodeIgniter:

Features in and of themselves are a very poor way to judge an application since they tell you nothing about the user experience, or how intuitively or intelligently it is designed. Features don’t reveal anything about the quality of the code, or the performance, or the attention to detail, or security practices. The only way to really judge an app is to try it and get to know the code. Installing CodeIgniter is child’s play so we encourage you to do just that. In the mean time here’s a list of CodeIgniter’s main features.

  • Model-View-Controller Based System
  • PHP 4 Compatible
  • Extremely Light Weight
  • Full Featured database classes with support for several platforms.
  • Active Record Database Support
  • Form and Data Validation
  • Security and XSS Filtering
  • Session Management
  • Email Sending Class. Supports Attachments, HTML/Text email, multiple protocols (sendmail, SMTP, and Mail) and more.
  • Image Manipulation Library (cropping, resizing, rotating, etc.). Supports GD, ImageMagick, and NetPBM
  • File Uploading Class
  • FTP Class
  • Localization
  • Pagination
  • Data Encryption
  • Benchmarking
  • Full Page Caching
  • Error Logging
  • Application Profiling
  • Scaffolding
  • Calendaring Class
  • User Agent Class
  • Zip Encoding Class
  • Template Engine Class
  • Trackback Class
  • XML-RPC Library
  • Unit Testing Class
  • Search-engine Friendly URLs
  • Flexible URI Routing
  • Support for Hooks, Class Extensions, and Plugins
  • Large library of “helper” functions

videos

Installing Code Igniter

 

CodeIgniter on cloud

Related Posts