The Working of Codeigniter Application Is Mentioned in A Simple Flowchart Given Below
The Working of Codeigniter Application Is Mentioned in A Simple Flowchart Given Below
Codeigniter installation is a very easy process. For the installation please follow the
given below steps:
• 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 [Link] file, you can configure the application. Using [Link] 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.
• Third_Party – The plugins can be placed in this folder for using it in your application.
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 “ [Link]” . 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 controller
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. The Controller Controls
Model as well as view.
Creating a Controller
Controller always stored inside Application/controllers folder. Condeigniter
provides two basic files that is stored
inside Application/controllers folder [Link] and [Link].
Keep these files as they are don't delete these files. Now Create a new file
under the same path(Application/controllers) named "[Link]"
<?php
class Hello extends CI_Controller
{
public function index()
{
echo "Hello World";
}
}
?>
Save Hello class inside Application/controllers/[Link]. Here, Hello class inherit
an in-built Codeigniter Class CI_Controller.
Points to Remember
Calling a Controller
• CI_Controller class must be extended Whenever u want to create Your own
Controller.
• Controller name must be Started with Capital letter
• Controller name and file name must be Similar
• Syntax
• [Link]
Output
Output About us
Codeigniter Views
Views
The view is a simple webpage(designing page) which called by Controller.
<!DOCTYPE html>
<html>
<head>
<title>About CI View</title>
</head>
<body>
<h1>About Codeigniter Views</h1>
</body>
</html>
$this->load->view('view_page_name');
Sometimes we can create different directly like user, admin etc. inside user
directory we may store header, footer,sidebar for users same as admin
inside admin directory, in this case we can call like :
$this->load->view('directory_name/view_page_name');
<?php
class Hello extends CI_Controller
{
public function index()
{
echo "Hello World";
}
public function about()
{
$this->load->view('about');
}
}
?>
Here Hello Controller has now 2 methods. One is index() that contains
"Hello World" message only. Second method about() is calling [Link]
view page. Note : inside Controller no need to call page extension of view.
Codeigniter Models
Models
Models are the classes designed to work with information in the database.
For example, if we are using CodeIgniter to manage users in our application
then we must have model class, which contains functions to insert, update,
display and delete data.
<?php
class Model_name extends CI_Model
{
public function __construct()
{
parent::__construct();
}
}
?>
Loading Model
Every Model class called/used inside a Controller. To call a model class
inside controller following code can be used
$this->load->model('model_name');
After loading model class inside Controller we can use other methods of
Model Class Syntax
$this->model_name->method_name();
Connecting to a Database
In CodeIgniter, We can connect with database in 2 ways. [Link]
Connecting - Automatic Connection can be done
using application/config/[Link]
$autoload['libraries'] = array('database');
$this->load->database();
Creating a Controller
Create a new file under the path Application/controllers/[Link] 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 Model
$this->load->model('Hello_Model');
}
public function savedata()
{
//load registration view form
$this->load->view('registration');
Creating a View
Create a new file under the path Application/views/[Link] 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);
}
}
Output : Database
Codeigniter display data from database
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');
}
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();
}
}
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");
}
}
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."'");
}
}
?>
Output
Codeigniter update database record
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');
}
<!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>
<th>Update</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 "<td><a href='updatedata?id=".$row->user_id."'>Update</a></td>";
echo "</tr>";
$i++;
}
?>
</table>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Registration form</title>
</head>
<body>
<?php
$i=1;
foreach($data as $row)
{
?>
<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" value="<?php echo $row-
>name; ?>"/></td>
</tr>
<tr>
<td>Enter Your Email </td>
<td><input type="text" name="email" value="<?php echo $row->email;
?>"/></td>
</tr>
<tr>
<td>Enter Your Mobile </td>
<td><input type="text" name="mobile" value="<?php echo $row->mobile;
?>"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="update" value="Update Records"/></td>
</tr>
</table>
</form>
<?php } ?>
</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."'");
}
function displayrecordsById($id)
{
$query=$this->db->query("select * from users where
user_id='".$id."'");
return $query->result();
}
function updaterecords($name,$email,$mobile,$id)
{
$query=$this->db->query("update users SET
name='$name',email='$email',mobile='$mobile' where user_id='".$id."'");
}
}
?>
Output(Display Records)
Output(Update Records)
Create registration form in codeigniter
name char(50)
email varchar(100)
password varchar(100)
mobile bigint
course char(100)
Controller
Copy the below given code in your User Controller. In this example we have not used proper
model page , all database query wrote in Controller.
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
if($this->input->post('register'))
{
$n=$this->input->post('name');
$e=$this->input->post('email');
$p=$this->input->post('pass');
$m=$this->input->post('mobile');
$c=$this->input->post('course');
}
$this->load->view('student_registration',@$data);
}
}
?>
Registration View
Copy the below given code in your student_registration.php View Page.
<!DOCTYPE html>
<html>
<head>
<title>Student Registration form</title>
</head>
<body>
<form method="post">
<table width="600" align="center" border="1" cellspacing="5"
cellpadding="5">
<tr>
<td colspan="2"><?php echo @$error; ?></td>
</tr>
<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 Password </td>
<td><input type="password" name="pass"/></td>
</tr>
<tr>
<td>Enter Your Mobile </td>
<td><input type="text" name="mobile"/></td>
</tr>
<tr>
<td>Select Your Course </td>
<td>
<select name="course">
<option value="">Select Course</option>
<option>PHP</option>
<option>Java</option>
<option>Wordpress</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="register" value="Register Me"/></td>
</tr>
</table>
</form>
</body>
</html>
email varchar(100)
password varchar(100)
mobile bigint
course char(100)
Controller
Copy the below given code in your User Controller.
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
if($this->input->post('login'))
{
$e=$this->input->post('email');
$p=$this->input->post('pass');
function dashboard()
{
$this->load->view('dashboard');
}
}
?>
Login View
Copy the below given code in your [Link] View Page.
<!DOCTYPE html>
<html>
<head>
<title>Login form</title>
</head>
<body>
<form method="post">
<table width="600" align="center" border="1" cellspacing="5" cellpadding="5">
<tr>
<td colspan="2"><?php echo @$error; ?></td>
</tr>
<tr>
<td>Enter Your Email </td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td width="230">Enter Your Password </td>
<td width="329"><input type="password" name="pass"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="login" value="Login"/></td>
</tr>
</table>
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Student Dashboard</title>
</head>
<body>
<h1>Welcome to your dashboard...</h1>
</body>
</html>
Output(Dashboard page)
name char(50)
email varchar(100)
password varchar(100)
mobile bigint
course char(100)
Controller
Copy the below given code in your User Controller.
<?php
class User extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
}
if($row)
{
$data['error']="<h3 style='color:red'>This user already
exists</h3>";
}
else
{
$data=array('student_id'=>'',
'name'=>$this->input->post('name'),
'email'=>$this->input->post('email'),
'password'=>$this->input-
>post('pass'),
'mobile'=>$this->input-
>post('mobile'),
'course'=>$this->input-
>post('course'));
$this->db->insert('student',$data);
}
$this->load->view('student_registration',@$data);
}
}
?>
Registration View
<!DOCTYPE html>
<html>
<head>
<title>Student Registration form</title>
</head>
<body>
<form method="post">
<table width="600" align="center" border="1" cellspacing="5"
cellpadding="5">
<tr>
<td colspan="2"><?php echo @$error; ?></td>
</tr>
<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 Password </td>
<td><input type="password" name="pass"/></td>
</tr>
<tr>
<td>Enter Your Mobile </td>
<td><input type="text" name="mobile"/></td>
</tr>
<tr>
<td>Select Your Course </td>
<td>
<select name="course">
<option value="">Select Course</option>
<option>PHP</option>
<option>Java</option>
<option>Wordpress</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="register" value="Register Me"/></td>
</tr>
</table>
</form>
</body>
</html>
This folder is the destination folder where image will store after Uploading .
Go to the root of the CI installation -> Create a folder named "upload". All
Imags will Store inside "Upload " Folder.
In this Controller, firstl I will load two "library" and Second I will load
a "Form helper" class, with the following code.
$this->load->library('form_validation');
$this->load->library(‘upload’);
$this->load->helper('url', 'form');
<?php
class ImageUpload_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
//load Helper for Form
$this->load->helper('url', 'form');
$this->load->library('form_validation');
}
function index()
{
$this->load->view('imageupload_form');
}
public function upload()
{
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2000;
$config['max_width'] = 1500;
$config['max_height'] = 1500;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('profile_pic'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('imageupload_form', $error);
}
else
{
$data = array('image_metadata' => $this->upload->data());
$this->load->view('imageupload_success', $data);
}
}
}
?>
Step 3 :View
For the Structure of image upload, I have created two files that is stored
inside Ci root view folder.
First file is to upload image and Second file is display Success message.
<!DOCTYPE html>
<html>
<head>
<title>Upload Image in Codeigniter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<?php echo @$error; ?>
<?php echo form_open_multipart('ImageUpload_Controller/upload');?>
<?php echo "<input type='file' name='profile_pic' size='20' />"; ?>
<?php echo "<input type='submit' name='submit' value='upload' /> ";?>
<?php echo "</form>"?>
</body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Image Uploaded Success</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Congreates image uploaded successfully</h1>
</body>
</html>
Output
[Link]
//old Code
$config['index_page'] = "[Link]”
//New updated code(Onlye Need to remove [Link] )
$config['index_page'] = ""
Step 2 We need to create .htaccess file and save inside Codeigniters Root
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ [Link]/$1 [L]
Output
How to use pagination in codeigniter
Pagination in Codeigniter with Step by Step
Example
Pagination basically implies the client can navigate the pages of results,
seeing a subset of them each time, as opposed to looking down the screen
for a very long time.
1. Database Configuration
2. Pagination Controller
3. Pagination Library
4. Pagination Model
Database Configuration
First of all we have to create a database and Store some dummy Records
inside the table. Inside a Single table we are going to store minumum 50
Records, and will display on View 10 Records on every page.
<?php
class StudentPagination_Model extends CI_Model
{
$this->load->helper('url','form');
$this->load->library("pagination");
$this->load->model('StudentPagination_Model');
}
$this->pagination->initialize($config);
$data["links"] = $this->pagination->create_links();
$data['student'] = $this->StudentPagination_Model-
>get_students($config["per_page"], $page);
$this->load->view('pagination', $data);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter Pagination Examples</title>
</head>
<body>
<div class="container">
<h2 class="text-primary">CodeIgniter Pagination Example</h2>
<table class="table table-bordered">
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Course</th>
</tr>
<tbody>
<?php foreach ($student as $res): ?>
<tr>
<td><?php echo $res->id ?></td>
<td><?php echo $res->name ?></td>
<td><?php echo $res->email ?></td>
<td><?php echo $res->course ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p><?php echo $links; ?></p>
</div>
</div>
</body>
</html>
The process of Form Validations helps in ensuring that the data that is submitted is correct to
store and process. Form Validations on server-side scripting are a little bit complex to handles
but Codeigniter handle the form validations much easily as it is having built-in library
functions to create forms validations.
$autoload['libraries'] = array('form_validation');
You can also load the helper and libraries inside the [Link] methods by
using:
While $autoload[ ] array helps in loading the library or helper automatically when the
application starts as it is a good practice to minimize the line of codes by not repeatedly using
same code.
Create View
Make a view file [Link] inside application/views/ This page will display the form and
which will be validated.
<html>
<head>
<title>Form</title>
</head>
<body>
<form>
<?php echo validation_errors(); ?>
<h5>Name</h5>
<input type = "text" name = "name" value = "<?php echo
set_value('name'); ?>" />
<h5>Email</h5>
<input type = "email" name = "email" value = "<?php echo
set_value('email'); ?>" />
<div><input type = "submit" value = "Submit" /></div>
</form>
</body>
</html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Form Submitted Successfully</h1>
</body>
</html>
Create Controller
Create a [Link] inside application/controller/
This page will show the form validations or print success message.
<?php
class FormController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form'));
$this->load->library(array('form_validation'));
}
public function form()
{
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('email','Email','required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('form');
}
else
{
$this->load->view('success');
}
}
}
?>
localhost/project_folder/formcontroller/form
Enter the credentials name and email, if you enter name and email it will show the success
page else give a validation error name and email is required.
Output
Explanation:
• form_validaton library in CodeIgniter helps in checking the type of error which has various
validation rules in it. We are using the required rule above which is a validation of a required
field. (for more validation rule reference checkout Codeigniter user guide)
• Form helper helps in the form task i.e. in system/helpers/form_helper.php which helps out
with some form functions.
• In [Link] view, the validation_errors(); function shows the form validation error which
occurs during wrong credentials input.
• In [Link] $this->form_validation->set_rules('name', 'Name', 'required'); $this-
>form_validation->set_rules('email', 'Email', 'required'); Sets the validation rule for the name
and email field inside the form. Here parameters passed by set_rules(); are
set_rules('name_field', 'validation_for' , 'type_of_rule')
• If the above condition is false i.e. the required condition is not satisfied and form is not filled
up then the validation is shown with the type of validation in the form view. If it is true then
it will redirect to the success page.
Maintaining the state helps in preserving the next request from the previous
one. Users don’t have to log in for each page, they can log in once and their
details are stored in a session with a session id of that user and then that
same data is reused for further request.
Codeigniter has a built-in class names ‘session’ for this purpose. The same
purpose of this session is to make the data available for the next request
made by the user.
Session Working:
When a page is requested by a user, the session class on the server checks
whether the cookie sent by the browser is valid or not. If the session cookie
is not valid or not available (expired or session expired) a new session is
created.
Session Initialization
With each page request/load on the site, session are globally run but to use
the data the initialization of session is done on the controller constructors
or can be auto-loaded in the system by session up ‘session’ in [Link]
Inside your controller you can load session by using this line of code:
$this->load->library('session');
$autoload['libraries'] = array(‘session’);
After the initialization of the session or loading session library, its object is
available using.
$this->session
$this->session->item
$this->session->userdata('item');
$var = $this->session->item;
OR
$var = $this->session->userdata('item');
$this->session->userdata();
$this->session->set_userdata('some_name', 'some_value');
$array = array(
'name' => 'believemaster',
'email' => 'believemasters@[Link]'
);
$this->session->set_userdata($array);
$this->session->has_userdata(‘value’);
If you want to remove name from the session which is a key value for the
session you can do it as:
$this->session->unset_userdata('name');
Unsetting the session can also be done in array format with the item key to
unset like this:
$array_list = (
'name',
'email'
);
$this->session->unset_userdata($array_list);
Session FlashData :
Session availability for only the next request and clearing it out
automatically after that is done using flash data. This is mostly used to
show one-time information i.e. error/success messages, information/status
messages, etc.
$this->session->keep_flashdata('success');
$this->session->keep_flashdata(array('error', 'success'));
$this->load->helper('url');
$this->load->libraries('session');
}
public function index()
{
$this->load->view('index');
}
Codeigniter supports multiple Protocols, Mail, send mail, and SMTP, multiple
recipients, CC and BCCs, HTML or Plain text email, Attachments, Word
wrapping and many more.
<?php
$config = array(
'protocol' => 'smtp',
'smtp_host' => '[Link]',
'smtp_port' => 465,
'smtp_user' => 'phptpoint@[Link]
',
'smtp_pass' => '123456',
'smtp_crypto' => 'ssl',
'mailtype' => 'text',
'smtp_timeout' => '4',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
?>
Note : for sending emails to work, you should provide valid configuration
parameters. Dummy parameters will not be able to send emails.
Create a View
Create a view file inside views/[Link]
<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter Email Send using SMTP</title>
</head>
<body>
<div>
<h3>Use the form below to send email</h3>
<form method="post" >
<input type="email" name="to" placeholder="Enter Receiver
Email">
<br><br>
<input type="text" name="subject" placeholder="Enter Subject">
<br><br>
<textarea rows="6" name="message" placeholder="Enter your
message here"></textarea>
<br><br>
<input type="submit" value="Send Email" />
</form>
</div>
</body>
</html>
CodeIgniter Controller
Create a Controller file inside controller/EmailController .php
<?php
class EmailController extends CI_Controller
{
$this->load->helper('url');
}
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 'Email has been sent successfully';
}
else
{
show_error($this->email->print_debugger());
}
}
}
?>
[Link]/main/home
[Link]/main/about
[Link]/main/contact
[Link]/main/login
[Link]/main/register
Routes are set after the base_url or the index_url with the controller and
method crated for routing to a specific page.
domain_name.com/Controller/Method/Parameter/
Example:
localhost/user/delete/2
User = Controller,
Delete = Method inside User Controller,
2 = Parameter that method takes
Setting Up Routes :
Create a new controller in application/controller [name should be the same
as listed in [Link] in this case [Link]]
Make a class with the same name as the controller and inside define a
method loading a view.
Application/views/[Link]
Usage of Routes:
To build large applications with complex URLs including all routing paths
along with the fetching of id makes the URL messy and is not at all user-
friendly, also it is not at all Search Engine [Link] convention in the
URL uses query methods to pass on the request along with the extension of
a page requested.
Ex:
[Link]/admin/[Link]?q=1
Which in response is so complex and long and for a user it makes no sense.
Users should get an idea of the content present on the page through its
URL.
The easier way it can be done is
[Link]/admin/user/1
which makes more sense about the page associated with it. Using routes
URL becomes cleaner and increase the user experience in routing the web.
Moreover, URL routing helps in creating routes that are SEO friendly for
reaching the page with a quick response.
For each function to work the controller will be the same i.e. blog and
methods inside are different. The working structure of this routing will work
something like this shown below:
Before creating a controller and view for the above structure to work.
Custom Url must be setup by creating routes for the project.
Open application/config/[Link] Add specific lines omitting the default
one.
$route[‘default_controller’] = ‘welcome’;
$route[‘blog’] = ‘blog’;
$route[‘blog/create’] = ‘blog/create’;
$route[‘blog/update/:id’] = ‘blog/update’;
$route[‘blog/delete/:id’] = ‘blog/delete’;
Explanation :
The lines on the right of equals sign are controllers and controller pointing
to the method they are calling and the lines on the left side of equals sign
defines its route where it is going or the url which is shown.
Therefore, in our scenario
After all the routes are set, make a controller for the blog that will respond
to the routes specified above. Inside application/controllers make new file
[Link] and following code:
<?php
class Blog extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(‘url’);
}
public function index()
{
$this->load->view(‘index’);
}
public function create()
{
$this->load->view(‘create’);
}
public function update($id)
{
$this->load->view(‘update’);
}
public function delete($id)
{
$this->load->view(‘delete’);
}
}
?>
Here Blog controller defines all the methods we mentioned in the routes i.e.
index, create, update, delete
Now just create views for all specific methods inside applications/views/
- [Link]
- [Link]
- [Link]
- [Link]
And echo out custom message on different page.
Inside [Link] and [Link] echo $id; to see the id which you pass as
the parameter in the URL.
Open up the browser and try the following
localhost/blog
localhost/blog/create
localhost/blog/update/1
localhost/blog/delete/1
This CodeIgniter tutorial pdf can help you to learn professional internet
applications development using the CodeIgniter framework.
Before starting with this tutorial, you need to be familiar with site
development using PHP and MySQL, We are assuming that you're aware of
core and advance PHP concepts.
DBMS Support Oracle, MS SQL, MySql, DB2, MySQL, Microsoft BI, MongoDB, PostgreSQL
PostgreSQL, JDBC addon with popular databases also used in
laravel.
Popularity Getting popular day by day Less popular than laravel but for building
with more developers fast small application with all security and
community and fast coding features it is prefered mostly.
style. Preffered mostly for large
projects with heavy features
and modules.
Modules Modularity for dividing project No built-in modularity like laravel. Modular
into different modules for easy extension used for creating and maintaing
workflow. modules.
HTTP support Can define HTTPs custom Does not fully support HTTPs
routes also specific URL for
each HTTPs route.
Testing Unit testing of code can be No built-in unit testing tools. Developers
done using PHPUnit. need to reply on other testing tools for
checking application code quality.
Learning Difficult for beginners to learn Easy and very much friendly to learn for
Curve as it is stuffed with features. beginners.
Here In this ajax form submit article, We will discuss about How to use ajax
post method in Codeigniter form insert, in this, we are going to use jquery
submit handler method with jquery validation rules for ajax form
submission and Jquery submit form ajax in Codeigniter will perform without
refresh whole page with validating form data on client-side.
CodeIgniter jQuery Ajax Post Data methods really made it easy to post data
and return that data without refreshing the page. We will show you apply
this jQuery Ajax post in CodeIgniter as well.
[Link](view)
<!DOCTYPE html>
<html lang="en">
<head>
<title>save data using Ajax</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="[Link]
<script
src="[Link]
t>
</head>
<body>
<div class="container">
<h1 align="center">Ajax Form using CI</h1>
<div class="form-group">
<label for="email">Enter Your Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter
Name" name="name">
</div>
<div class="form-group">
<label for="email">Enter Your Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter
Email" name="email">
</div>
<div class="form-group">
<label for="email">Enter Your Course:</label>
<input type="text" class="form-control" id="course" placeholder="Enter
course" name="course">
</div>
<input type="button" class="btn btn-primary" value="save data"
id="butsave">
</div>
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#butsave").click(function()
{
var name = $('#name').val();
var email = $('#email').val();
var course = $('#course').val();
},
error:function()
{
alert('data not saved');
}
});
}
else
{
alert("pls fill all fields first");
}
});
});
</script>
</body>
</html>
AjaxController(Controller)
<?php
class AjaxController extends CI_Controller
{
$data = array(
'name' => $this->input->post('name'),
'email'=>$this->input->post('email'),
'course'=>$this->input->post('course')
);
$this->load->model('AjaxModel');
$result=$this->AjaxModel->saveData($data);
if($result)
{
echo 1;
}
else
{
echo 0;
}
}
}
?>
AjaxModel(Model)
<?php
class AjaxModel extends CI_Model
{
public function saveData($data)
{
if($this->db->insert('student',$data))
{
return 1;
}
else
{
return 0;
}
}
}
?>
Output
[Link](View)
Save "[Link]" inside view folder
<!DOCTYPE html>
<html lang="en">
<head>
<title>Username availability check using Codeigniter, AJAX and MySQL</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="[Link]
<script
src="[Link]
t>
</head>
<body>
<div class="container">
<h3 class="text-center text-primary">Username availability check using
Codeigniter, AJAX </h3>
<div class="form-group">
<label for="email">Enter Your Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter
Name" name="name">
</div>
<div class="form-group">
<label for="email">Enter Your Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter
Email" name="email">
<label id="msg"></label>
</div>
<div class="form-group">
<label for="email">Enter Your Course:</label>
<input type="text" class="form-control" id="course" placeholder="Enter
course" name="course">
</div>
<input type="button" class="btn btn-primary" value="save data"
id="butsave">
</div>
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#email").blur(function()
{
var email = $('#email').val();
if(email!="")
{
[Link]({
type: "POST",
url: "<?php echo
base_url('/[Link]/AjaxController/checkUser'); ?>",
dataType: 'html',
data: {email: email},
success: function(res)
{
if(res==1)
{
$("#msg").css({"color":"red"});
$("#msg").html("This user already exists");
}
else
{
$("#msg").css({"color":"green"});
$("#msg").html("Congrates username available !");
},
error:function()
{
alert('some error');
}
});
}
else
{
alert("pls enter your email id ");
}
});
});
</script>
</body>
</html>
[Link](Controller)
Save "[Link]" inside controller folder
<?php
class AjaxController extends CI_Controller
{
$email=$this->input->post('email');
$this->load->model('AjaxModel');
$result=$this->AjaxModel->checkuser($email);
if($result)
{
echo 1;
}
else
{
echo 0;
}
}
}
?>
[Link](Model)
Save "[Link]" inside Model folder
<?php
class AjaxModel extends CI_Model
{
public function checkuser($email)
{
$this->db->where('email',$email);
$query=$this->db->get('student');
if($query->num_rows()>0)
{
return 1;
}
else
{
return 0;
}
}
}
?>
Output
:
CodeIgniter Strong Password Validation
For example, Set the minimum and maximum length of the password, It should
contain a lowercase, uppercase, numbers, and special chars. You can also easily
make sure that the data entered in the password field Should be equal to
password confirmation field.
• Required
• Lowercase
• Uppercase
• Number
• Special Chars
[Link](view)
<!DOCTYPE html>
<html>
<head>
<title>Strong Password Validation</title>
<link rel="stylesheet"
href="[Link]
<script
src="[Link]
</head>
<body>
<div class="container-fluid ">
<div class="row">
<div class="col-md-9 offset-md-1">
<div class="user_about_content_box">
<div class="tab-pane">
<h3>Strong Password Validation</h3>
</div>
<div class="col-md-8">
<?php
if($this->session->flashdata('success'))
{
echo "<span class='text-success' style='font-weight:bold'>".$this->session-
>flashdata('success')."</span>";
}
?>
</div>
<form method="post" action="<?php echo
base_url('passwordcontroller/index'); ?>">
<div class="col-md-8">
<div class="form-group" id="prime_cat">
<input type="email" value="<?php echo set_value('email'); ?>"
name="email" class="form-control input-group-lg" placeholder="Email">
</div>
<?php if(form_error('email')){echo "<span
style='color:red'>".form_error('email')."</span>";} ?>
</div>
</div>
</div>
</div>
</body>
</html>
[Link](Controller)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class PasswordController extends CI_Controller
{
$rules = array(
[
'field' => 'email',
'label' => 'Email',
'rules' => 'required',
],
[
'field' => 'new_password',
'label' => 'New Password',
'rules' => 'callback_valid_password',
],
[
'field' => 'confirm_password',
'label' => 'Confirm Password',
'rules' => 'matches[new_password]',
],
);
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==FALSE)
{
$this->load->view('PasswordValidation');
}
else
{
$this->session->set_flashdata('success','Congrates ');
redirect(base_url('PasswordController/index'));
}
$regex_lowercase = '/[a-z]/';
$regex_uppercase = '/[A-Z]/';
$regex_number = '/[0-9]/';
$regex_special = '/[!@#$%^&*()\-_=+{};:,<.>ยง~]/';
if (empty($password))
{
$this->form_validation->set_message('valid_password',
'The {field} field is required.');
return FALSE;
}
return FALSE;
}
return FALSE;
}
return FALSE;
}
return FALSE;
}
if (strlen($password) < 5)
{
$this->form_validation->set_message('valid_password',
'The {field} field must be at least 5 characters in length.');
return FALSE;
}
return FALSE;
}
return TRUE;
}
//strong password end
Output(validation
error)
Output(validation success
message)
Import CSV Data into Mysql in
Codeigniter
This CSV Import features makes it easy to insert a bunch of data in the
database on a single click.
Through this tutorial, we are going to show you how to import CSV file data
into MySQL database in CodeIgniter.
Controller(Csv_import.php)
function index()
{
$this->load->view('csv_import');
}
function display_data()
{
$result = $this->csv_import_model->select();
$output = '
<h3 align="center">User Details Imported from CSV</h3>
<div class="table table-bordered">
<table class="table table-bordered table-striped">
<tr>
<th>[Link]</th>
<th>Name</th>
<th>Email</th>
<th>Mobile</th>
</tr>
';
$count = 0;
if($result->num_rows() > 0)
{
foreach($result->result() as $row)
{
$count = $count + 1;
$output .= '
<tr>
<td>'.$count.'</td>
<td>'.$row->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->phone.'</td>
</tr>';
}
}
else
{
$output .= '
<tr>
<td colspan="5" align="center">Data not Available</td>
</tr>
';
}
$output .= '</table></div>';
echo $output;
}
function import_csv()
{
$file_data = $this->csvimport->get_array($_FILES["csv_file"]["tmp_name"]);
foreach($file_data as $row)
{
$data[] = array(
'name' => $row["Name"],
'phone' => $row["Phone"],
'email' => $row["Email"]
);
}
$this->csv_import_model->insert($data);
}
}
Model(Csv_import_model.php)
<?php
class Csv_import_model extends CI_Model
{
function select()
{
$this->db->order_by('id', 'DESC');
$query = $this->db->get('tbl_user');
return $query;
}
function insert($data)
{
$this->db->insert_batch('tbl_user', $data);
}
}
View(csv_import.php)
<html>
<head>
<title>How to Import CSV Data into Mysql using Codeigniter</title>
<script
src="[Link]
<link rel="stylesheet"
href="[Link] />
<script
src="[Link]
>
</head>
<body>
<div class="container box">
<h3 align="center">How to Import CSV Data into Mysql using Codeigniter</h3>
<script>
$(document).ready(function(){
load_data();
function load_data()
{
$.ajax({
url:"<?php echo base_url(); ?>csv_import/display_data",
method:"POST",
success:function(data)
{
$('#imported_csv_data').html(data);
}
})
}
$('#import_csv').on('submit', function(event){
[Link]();
$.ajax({
url:"<?php echo base_url(); ?>csv_import/import_csv",
method:"POST",
data:new FormData(this),
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#import_csv_btn').html('Importing...');
},
success:function(data)
{
$('#import_csv')[0].reset();
$('#import_csv_btn').attr('disabled', false);
$('#import_csv_btn').html('Import Done');
load_data();
}
})
});
});
</script>
Output(Before
Uploading)
Output(after
Uploading)
You can either use fputcsv() PHP method or directly write the comma-separated
content on the file in PHP for creating CSV file.
In this tutorial, We are going to guide you how you can export MySQL data in CSV
file in CodeIgniter project.
Controller([Link])
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// get data
$usersData = $this->ExportModel->getUserDetails();
// file creation
$file = fopen('php://output', 'w');
$header = array("srno","Name","Mobile","Email");
fputcsv($file, $header);
fclose($file);
exit;
}
}
Model([Link])
$response = array();
// Select record
$this->db->select('*');
$q = $this->db->get('tbl_user');
$response = $q->result_array();
return $response;
}
}
}
View(export_view.php)
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script
src="[Link]
<link rel="stylesheet"
href="[Link] />
<script
src="[Link]
>
<title>Export MySQL data to CSV file in CodeIgniter</title>
</head>
<body>
Controller(application/controllers/[Link])
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
}
?>
Model(application/models/[Link])
<?php
class PdfModel extends CI_Model
{
function showRecord()
{
return $this->db->get('tbl_users');
}
function show_single_details($customer_id)
{
$this->db->where('UserID', $customer_id);
$data = $this->db->get('tbl_users');
$output = '<table width="100%" cellspacing="5" cellpadding="5">';
foreach($data->result() as $row)
{
$output .= '
<tr>
<td width="25%"><img
src="'.base_url().'images/'.$row->images.'" /></td>
<td width="75%">
<p><b>Name : </b>'.$row->Name.'</p>
<p><b>Address : </b>'.$row-
>Address.'</p>
<p><b>City : </b>'.$row->City.'</p>
<p><b>Postal Code : </b>'.$row-
>PostalCode.'</p>
<p><b>Country : </b> '.$row->Country.'
</p>
</td>
</tr>
';
}
$output .= '</table>';
return $output;
}
}
?>
View(application/views/[Link])
<html>
<head>
<title>Generate PDF using Dompdf</title>
<link rel="stylesheet"
href="[Link] />
</head>
<body>
<div class="container box">
<h2 class="text-center text-primary">Generate PDF using
Dompdf</h3>
<br />
<?php
if(isset($customer_data))
{
?>
<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Name</th>
<th>View</th>
<th>View in PDF</th>
</tr>
<?php
foreach($customer_data->result() as $row)
{
echo '
<tr>
<td>'.$row->UserID.'</td>
<td>'.$row->Name.'</td>
<td><a
href="'.base_url().'[Link]/pdfcontroller/details/'.$row-
>UserID.'">View</a></td>
<td><a
href="'.base_url().'[Link]/pdfcontroller/pdfdetails/'.$row->UserID.'">View in
PDF</a></td>
</tr>
';
}
?>
</table>
<?php
}
if(isset($customer_details))
{
echo $customer_details;
}
?>
</div>
</body>
</html>
Library(application/libraries/[Link])
<?php
error_reporting(1);
if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once 'dompdf/[Link]';
use Dompdf\Dompdf;
?>
Output(Display All
Records)
In this article, we can see how to create a fully customized 404 error page
in CodeIgniter. It makes a web application user-friendly and helps the user
to go back to your website. When the user clicks on the broken link or non-
existent URL, an error message appears on the screen. A very common
cause of this situation is the broken links that point to pages or resources
that have been removed (or taken down) by the website administrator,
most of the visitors may leave your site, to overcome this problem custom
404 error page gives an opportunity to display a customized message page
with homepage redirect link.
Mainly the broken links are responsible for showing the 404(Page not found)
error page occurred. You can easily customize the 404 error page as per
your needs in CodeIgniter.
In this tutorial, we will see how to create a simple custom 404 error page in
CodeIgniter. For this, you need to create an HTML of your 404-error page.
For this, you have to Go to your web application directory and open the
file application/views/errors/html/error_404.php file in the editor. replace
error_404.php code with given below code.
After customizing error_404.php file, we will see that the custom 404 pages
have appeared like this
Output
<?php
$Mydata = array(
array(
'name' => 'Your Name' ,
'email' => 'Your Email' ,
'course' => 'Your Course'
),
array(
'name' => 'Your Name' ,
'email' => 'Your Email' ,
'course' => 'Your Course'
)
);
$this->db->insert_batch('mytable', $Mydata);
//OR
$post = $this->input->post();
for ($i = 0; $i < count($post['name']; $i++)
{
$this->db->insert('my_table', array('name' => $post['name'][$i], 'email' =>
$post['email'][$i], 'course' => $post['course'][$i]));
}
?>
<?php } ?>
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('AdminModel');
//$this->load->helper('url');
}
public function center_details()
{
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/center_emp_details');
}
else
{
$post = $this->input->post();
for ($i = 0; $i < count($post['Name']); $i++)
{
$data=array('name' => $post['Name'][$i],
'department' =>
$post['Depmt'][$i],
'course' =>
$post['course'][$i],);
$this->db->insert('salary',$data);
}
}
}
}
?>
Output
It is one of the easiest ways to upload multiple images with [Link] the person
thinks about uploading the image on the web sites, then the first question strikes in his mind
is how to upload images in Codeigniter.
Here is the list of steps that will be helpful for you to image upload and display in
Codeigniter.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Image extends CI_Controller
{
public function index()
{
$this->load->view('image');
}
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter multiple drag and drop image upload</title>
<script
src="[Link]
<link rel="stylesheet"
href="[Link]
<link
href="[Link]
rel="stylesheet">
<script
src="[Link]
script>
</head>
<body>
<div class="container">
<div class="row form-group">
<form action="<?php echo base_url('Image/imageUploadPost'); ?>"
enctype="multipart/form-data" class="dropzone" id="image-upload" method="POST">
<div class="col-md-12">
<h2 class="text-primary">Codeigniter multiple drag and
drop image upload</h2>
<div>
<h3 class="text-warning">Upload Multiple
Image By Click On Box</h3>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<input class="btn btn-primary btn-lg"
type="submit" value="upload"/>
</form>
</div>
</div>
</div>
<script type="text/javascript">
[Link] =
{
maxFilesize:1,
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
</script>
</body>
</html>