• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / Beginning Codeigniter Application Development

Beginning Codeigniter Application Development

May 2, 2011 by Rana Ahsan 53 Comments

CodeIgniter Tutorial

I have already written few articles on codeigniter, however, didn’t written for the genuine beginners yet. But, as i have written many beginner level tutorials here, i think, a beginners tutorial on codeigniter will be also helpful for my blog readers. At the time of writing, the latest codeigniter version is 2.0.2 . I am going to use this version for today’s tutorial. This tutorial is intended to the developers who are absolute beginners on codeigniter and want to have a better start very quickly.

Prerequisites:

However, prior using codeigntier, its required that you know what mvc design pattern is. To more about mvc, you can start with the wiki article on mvc .

Also, wish you have already xampp/wamp or something similar already set up in your computer. Now, Download the latest version of codeigniter. extract it and copy the directory to the root of your local server. without doing anything else, you should be able to run this and see a page like as follows from this local url: http://localhost/codeigntier/

Running Codeigniter Firsttime

Read The Complete PHP CodeIgniter Tutorials Series By CodeSamplez.com

Directory Structure:

The application directory structure is mainly consists of 2 directory, ‘system’ and ‘application’.

Codeigniter Root Directory Structure

The ‘system’ directory is the core and consists of the core framework files. When a new version is released, you can update your existing application just by replacing this system directory with the latest release. We won’t never going to work on this folder our selves ever. All our codes are going to take place in the ‘application directory’. There you will see a list of sub directories as like the following image:

codeigniter application directory structure

Lets get a little familiar with the directories:

  • Cache : This directory will contain all kinds of cached files if you are using so. However, you will may need to provide write access for the application to this directory as codeigniter will need to create temporary files on this folder. To know how to use caching, please refer to codeigniter caching tutorial.
  • Config : This directory includes settings/configuration related information like database settings, route information, constants declaration, items to be auto loaded etc. To know more, please visit codeigniter documentation about using config class .
  • Controller : This directory includes all controller definitions. It can be said as the entry point of application also, every requests triggers a certain method of a controller.
  • Core : If we need to extend the functionality of any core classes like controller,loader,router etc, then we can declare new class here which will extend those core classes and put the implementation inside those.
  • Errors : This directory includes some basic template for showing various kind of errors like db error, php errors, 404 errors etc, which we can change later as per our requirements.
  • Helpers : This directory will include all helper files. Read more about using helpers.
  • Hooks : This directory will include all hooks declaration. Read more about using hooks
  • Language : This directory will include language files. By loading different language files, we can make our application multilingual supported. Read more about using language class.
  • Libraries : This directory will include all library class files that might need to be created for our applications.
  • Logs : This directory will include all application logs. TO know how to write log for debug/error/info, please more about error handling
  • Migrations : This directory will include migration helpers.
  • Models : This directory will include all model classes used in our application. This section can be said as the ‘data access layer’ of our application.
  • Third_party : This directory will include library files, but only those, which are imported from third-party. So, difference between the ‘third_party’ and ‘libraries’ is that, one is for self-made libraries, for app specific, other one is for importing party libraries.
  • Views : This directory will include all view template files.

Application URL Structure:

Codeigniter uses a very easy and handy url structure scheme. and it is completely inter-related with the controller class name and method name. to access a controller method, you have to use url like {root_url}/index.php/{controller_name}/{method_name}. To know more in details, please refer to the codeigniter url structure documentation .

Create A Basic Controller:

Lets start by making a basic controller class file. Create a new file in the ‘controllers’ directory and name it ‘blog.php’. Here is the code snippet for this controller class:

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

class Blog extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/blog
	 *	- or -  
	 * 		http://example.com/index.php/blog/index
	 *	- or -	
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/blog/{method_name}
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		echo "Hello World";
	}
}

/* End of file Blog.php */
/* Location: ./application/controllers/blog.php */

Now, run the application with the url “http://localhost/ci_app/index.php/blog”, you will see the sentence ‘Hello World’ on the page. ‘index’ the default method that is being executed when no other method is specified in url. And we understood one thing clearly, to create a page, we may ignore to have a model and/or a view file, but we must need a controller.

Create a model :

Lets create a simple model on our application. We won’t cover any database activity on this tutorial. But, its pretty easy. setup your database server info on the ‘config/database.php’. Then you can access database in either straight cut way or use codeigniter provided ‘active record’ library that helps a lot creating/executing SQL query easily. You can read more on my another article about codeigniter active record class. Here is the code of the model class we will be using:

if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Blogmodel extends CI_Model{

    /**
     * returns a list of articles
     * @return array  
     */
    function get_articles_list(){
        $list = Array();
        
        $list[0] = (object)NULL; 
        $list[0]->title = "first blog title";
        $list[0]->author = "author 1";

        $list[0] = (object)NULL;
        $list[1]->title = "second blog title";
        $list[1]->author = "author 2";

        return $list;
    }
}
?>

Modify The Controller:

To use the data from model, lets change our controller code that will receive data from model and send it to the view for final rendering. Here is the modified version of the controller:

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

class Blog extends CI_Controller {

	public function index()
	{
            $this->load->model("blogmodel");   
            $articles = $this->blogmodel->get_articles_list();            
            $data["articles"] = $articles;
            $this->load->view('blog/index',$data);
	}
}

Create A View:

Lets create a simple view file that will show the data we get from the ‘blogmodel’ in a basic HTML template. Following is the template code:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<title>Welcome to Blog Page</title>

<style type="text/css">
body {
 background-color: #fff;
 margin: 40px;
 font-family: Lucida Grande, Verdana, Sans-serif;
 font-size: 14px;
 color: #4F5155;
}

a {
 color: #003399;
 background-color: transparent;
 font-weight: normal;
}

h1 {
 color: #444;
 background-color: transparent;
 border-bottom: 1px solid #D0D0D0;
 font-size: 16px;
 font-weight: bold;
 margin: 24px 0 2px 0;
 padding: 5px 0 6px 0;
}

code {
 font-family: Monaco, Verdana, Sans-serif;
 font-size: 12px;
 background-color: #f9f9f9;
 border: 1px solid #D0D0D0;
 color: #002166;
 display: block;
 margin: 14px 0 14px 0;
 padding: 12px 10px 12px 10px;
}

</style>
</head>
<body>
<h1>Welcome To my blog</h1>
<?php
foreach($articles as $article)
{
?>
<h3><?php echo $article->title; ?></h3>
By <strong><?php echo $article->author; ?></strong>
<?php
}    
?>
</body>
</html>

Calling a view from controller:

The above “Modify The Controller” already demonstrates how to call a view. However there are few things you will need to remember. A traditional codeigniter view is a simple php file with “.php” extension. You can place it anywhere inside the “views” directory. Just, you will have to mention the correct path inside the ‘views’ directory. Like if you have a view inside a “blog” directory(which resides in ‘views’ directory, of course). Then you will have to pass the view parameter as follows:

$this->load->view("blog/template_name");

Notice that, we haven’t use any extension(here .php) for the template name as it recognize it automatically.

Another important thing to remember is that, the second parameter is optional to call the view. If you have any data to pass to view, then pass it through the second parameter. If you haven’t, then you won’t have to pass any second parameter at all.

Also, data that are passed to view are parsed from associated array. Lets say, we are assigning and passing some data from controller to view. The controller code is as follows:

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

class Test extends CI_Controller {

	public function index()
	{           
            $data["name"] = "Md Ali Ahsan Rana";
            $data["designation"] = "Software Engineer"; 
            $this->load->view('test',$data);
	}
}

The view code is as follows:

<!-- File name: test.php -->
<!-- Location: application/views/test.php -->

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Welcome to Test Page</title>
</head>
<body>
<h2>My Name is <?php echo $name; ?></h2>
<h2>My Designation is <?php echo $designation; ?></h2>
</body>
</html>

Notice that, every associative key from $data becomes as a variable on the view section. So, any data variable you may need on your view, you will have to wrap it with a common variable’s associative index(here $data variable) and finally pass this wrapper variable. Codeigniter will parse it automatically to its corresponding component variables.

References:

As long as you know the basics, best place to know in details is the codeigniter documentation. There you will find in details about every thing with examples also. I found it as one of the best documentation on web. You can ask any kind of question related to codeigniter on their official forum.

Also don’t forget to checkout my codeigniter tutorials series for detailed tutorial with example on various specific areas of this popular framework! Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: codeigniter, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. Chuck says

    November 21, 2011 at 10:51 am

    First example works but the rest of the examples are lacking file names, etc. so not of much use as a beginner tutorial.

    Reply
    • Rana says

      November 21, 2011 at 11:50 am

      Are you having issues? Can you please explain what? Then I can try to solve it and also update the tutorial for being more helpful for future seekers. Thanks..

      Reply
      • francis says

        September 21, 2014 at 10:21 pm

        Thanks for this…Like it

        Reply
    • as says

      July 2, 2015 at 3:11 am

      Nice One. Thanks..

      Reply
    • talentedaamer says

      October 1, 2015 at 5:56 am

      the name of the file should be similar to its class name,

      for example if we have a class blog the controller should be blog.php this way you will not get error.

      Reply
  2. Gokul Raj says

    November 21, 2011 at 11:58 pm

    How to create new controller.

    Reply
    • Rana says

      November 22, 2011 at 12:34 am

      Hi, Please refer to “Create A Basic Controller” section. Please let me know f you don’t understand anything..

      Reply
      • Gokul Raj says

        November 22, 2011 at 1:06 am

        Thanks Rana. Then i have another doubt how to create admin for cms. I created admin folder in controller. If i typed browser i have error page not found. What i do Rana.

        Reply
        • Rana says

          November 22, 2011 at 4:50 am

          Hi, well, you will have to study a little about how codeigniter urls work and also how you can customize the routing. Please refer to http://codesamplez.com/development/codeigniter-routes-tutorial and its references to codeigniter user guide for details. Finally, seems like, you are facing issue similar to this one: http://stackoverflow.com/questions/8143997/codeigniter-2-0-x-controller-subdirectories-default-controller-needs-to-be-in . There is a solution already, refer to that. Hope these helps. Thanks.

          Reply
  3. suresh says

    December 28, 2011 at 5:00 am

    that’s good

    Reply
    • MichaelB says

      January 1, 2012 at 5:43 pm

      The first section does work, then the rest of the article becomes unclear.

      1. In the section “Create a model”, what should be the filename of that file?
      2. In the section “Create A View”, what should be the filename of that?

      Reply
      • Rana says

        January 1, 2012 at 11:19 pm

        Hi MichaelB, There is no specific restriction to the naming convention for model/view(or even controller). You can use any name, just you will have to remember to extend them from their corresponding base class. Like, if you are creating a model, you must have to inherit the “CI_Model” class, to get the characteristics of a regular Codeigniter model. In case of view, just name the template any name and then call it from controller with data(if any), Like as follows:

        $this->load->view(“template_name”,$data);

        I will edit the tutorial for calling a view from controller. Seems it will may helpful to some other guys like you. Thanks for pointing out is.

        Reply
  4. ITGuy says

    January 18, 2012 at 3:00 pm

    Really great programming abilities you\’ve there. i\’m a programmer myself but I still require to learn until I reach your ability. great article!

    Reply
  5. best free web services says

    February 11, 2012 at 7:04 am

    Wow, nice post buddy. It can help me to develop website using codeigniter framework.

    Reply
  6. Haider says

    February 18, 2012 at 2:58 am

    thank you very much
    it give me complete inside out to the MVC as well as codeignighter
    thanks you very very much

    Reply
  7. kvkbharadwaz says

    February 22, 2012 at 10:04 am

    this helped me a lot buddy and moreover your site interface is really good and CLEAN.

    keep up the good work.

    Reply
  8. bari says

    February 28, 2012 at 9:27 pm

    hi rana, i have problem with include php file. i use include(), require() and require_once(). but none of them works.
    i have a php file that contain only variables, so much variables. and i want to include the file to passing variables.
    how i supposed to do. pls help me.
    the ci directory:
    -application
    -system
    -user_guide
    -style
    -include_folder

    and my file in include_folder directory.

    thanks in advance.

    Reply
    • Rana says

      March 2, 2012 at 4:21 am

      try using:

      APPPATH.”/include_folder/file_name.php”

      Reply
  9. balaji says

    April 2, 2012 at 1:00 am

    it vary good for fresher + inretmideate

    Reply
  10. kamal says

    June 4, 2012 at 11:33 pm

    hello Rana,
    I’m a beginer in CI my problem is how to load jquery library in the current version of CI and how to apply a common CSS styling sheet to all my views

    Reply
  11. Jhon says

    June 25, 2012 at 12:07 am

    Thanx Rana for providing these Tuts these are very useful for everyone especially fresher

    Reply
  12. pratik says

    July 26, 2012 at 10:55 pm

    great,i have one problem i want to pass the more then one query from the model and get in controller.now i want to some additional work on that query and pass to the view.how can i do that.thanks

    Reply
  13. john says

    August 12, 2012 at 9:24 am

    Very useful especially on passing data to the view and how the keys of the associative array are automatically turned into variables in the view.

    Reply
  14. julieancordova says

    March 10, 2013 at 5:22 am

    what would be the best IDE for code igniter?
    where I can use breakpoints,

    Reply
  15. Raza says

    May 30, 2013 at 2:43 am

    the first program for blog.. throws an error more of a warnin. creating default object on empty value..

    Reply
    • Md Ali Ahsan Rana says

      May 30, 2013 at 3:52 am

      Hello Raza, it seems like you php compatibility error. This exercize was written with php 5.3.x and you are probably using php 5.4 , right? Just initialize all the variables at first (example: $test = (object)NULL) solves the problem in most cases. If you are still not sure what to do, can you give the error line number or a screenshot link? Thanks.

      Reply
  16. Nadimuthu says

    November 29, 2013 at 9:57 am

    How to configure with lamp? Anyone please help me..

    Reply
  17. Azhar says

    December 28, 2013 at 9:36 pm

    i have this problem. I have created a views/templates/navbar.php using bootstrap. the bootstrap is located in the root directory assets/bootstrap. I called the navbar.php through the default controller (news). It works.

    Then I create another views/templates/page.php. I created a function create_cosec in the default controller with $this->load->view(‘navbar’); and $this->load-view(‘page.php’); . I wish the page will display the navbar on the top follow by the page details.

    When I call the page localhost/index.php/news/ create_cosec ==>the page is display correctly but the navbar displayed but without the bootstrap functionalities. It seems that codeigniter doesn’t know where is the assets/bootstrap directory?

    Is it URL issues?
    Thanks

    Reply
  18. D R says

    May 12, 2014 at 3:44 pm

    Good framework to work with, also believe in learning the pure php language too, and also try to learn other frameworks so that you keep yourself on top of development.

    Reply
  19. Lucky Bhumkar says

    August 19, 2014 at 1:41 pm

    Good explanation..but lacks screenshots.

    Reply
  20. Michael says

    August 27, 2014 at 7:08 am

    How about some explanation of the root folders like “Source files”… what other folders are at this level? I’m looking at it from a continuous deployment point of view.

    Reply
  21. mwamba says

    September 16, 2014 at 8:57 am

    its giving error
    A PHP Error was encountered

    Severity: Warning

    Message: Creating default object from empty value

    Filename: models/blogmodel.php

    Line Number: 12

    in the list model

    Reply
    • Md Ali Ahsan Rana says

      September 16, 2014 at 9:01 pm

      That is because of php version, I assume. Should be fixed by using ‘$list = (object)NULL;’ . Hope this helps.

      Reply
  22. Lilly says

    January 30, 2015 at 3:06 am

    Excellent Tutorial !! Helps alot.

    Reply
  23. bakhtiar khan wazir says

    February 12, 2015 at 12:33 am

    Good and understandable tutorial

    Reply
  24. Malik Ahmad says

    February 15, 2015 at 5:59 am

    Thanks for tutorial 🙂
    so nice

    Reply
  25. Sandeep says

    February 23, 2015 at 2:58 am

    Hi Md Ali Ahsan Rana,

    I’m getting an error “fetching ajax content” when i run my application in my local server xammp and also getting error each time when i refresh the pages of my project.

    waiting for your response

    thanks!

    Reply
    • Md Ali Ahsan Rana says

      February 23, 2015 at 7:31 pm

      There isn’t any ajax related code been shared on this tutorial. So, I am assuming, you are trying in a little different way. Thus I will suggest you to share your code/more info in some kind of code sharing site and put the link here. This will help to understand your issue more better.

      Reply
  26. Tharindu Dissanayake says

    March 12, 2015 at 3:55 am

    nice tutorials.. thanks Mr.Rana

    Reply
  27. skemas says

    April 6, 2015 at 11:24 pm

    have entered $list = (object)NULL; but returns an errror:

    Fatal error: Cannot use object of type stdClass as array in C:\xampp\blog\codeigniter\application\models\blogModel.php on line 13

    Where should i place the line of code? Thanks! Greate tutorial for beginners

    Reply
    • Md Ali Ahsan Rana says

      April 7, 2015 at 2:37 pm

      I guess, that’s because of your PHP version. You can try with ‘Array()’/’array()’ instead of ‘(object)NULL’, if you are using older versions of PHP. Hope that helps.

      Reply
  28. Syed Sajid Ali says

    June 14, 2015 at 1:21 pm

    Please tell me how we load multiple pages in ci

    Reply
  29. Saranya Mani says

    June 24, 2015 at 6:09 am

    Hi,
    I am Saranya.
    I worked lot on CMS, i want to learn Framework that too particularly code igniter, Please guide me how to learn from where to learn etc…

    Reply
  30. shilp says

    September 2, 2015 at 1:52 am

    hi,
    i have a query. i just installed codeigniter using composer ( $ composer require “rogeriopradoj/codeigniter 2.2.1-rc.2” ) There i got folder structure on root
    -application
    -vendor
    and system file was in vendor folder. I m quite confused whats the se of this vendor folder. And how to start project . Please help me out

    Reply
  31. ArunValaven says

    December 18, 2015 at 6:12 am

    Hai Rana.. There is in need to change the code from $list[0] = (object)NULL; to $list[1] = (object)NULL; in its second occurrence in “Create a model topic”. Array index value need to change from “0” to “1” to get escape from error in displaying output. Thanks for your simple and clear explanation about CodeIgniter.

    Correct code:
    $list[0] = (object)NULL;
    $list[0]->title = “first blog title”;
    $list[0]->author = “author 1”;

    $list[1] = (object)NULL;
    $list[1]->title = “second blog title”;
    $list[1]->author = “author 2”;

    Reply
  32. Amandeep Singh says

    February 11, 2016 at 6:38 am

    Thanks sir for this blog

    Reply
  33. rady says

    February 14, 2016 at 10:45 pm

    Hi Mr.Rana
    I hope this blog so good for beginner CI like me.
    Thank you.

    Reply
  34. Haseem Mujahidh says

    April 4, 2016 at 8:48 am

    thank you,Highly appreciate if you use file name and paths in your tutorial,then it would be a absolute beginners guide.

    Reply
  35. mariam says

    July 8, 2017 at 8:09 pm

    thank you for this… I will bookmark for the future

    Reply

Trackbacks

  1. Using Smarty With Codeigniter | codesamplez.com says:
    June 7, 2011 at 11:47 am

    […] on June 7, 2011 Tweet Before, I have written tutorials about smarty basics as well as codeigniter basics. Today, in this tutorial, i will try to guide you through how to integrate smarty template engine […]

    Reply
  2. Codeigniter Bundle With Popular Libraries And Best Practices | codesamplez.com says:
    December 19, 2012 at 9:08 am

    […] should first get familiar with Codeigniter then come back here. You can start with my article on Codeigntier tutorial for beginners […]

    Reply
  3. Guidelines And Best Practices For Codeigniter Development | codesamplez.com says:
    December 20, 2012 at 3:12 am

    […] know it more or less. If you are a beginner, I will strongly recommend that you better start with beginning codeigniter application development tutorial […]

    Reply
  4. Using Doctrine ORM With Codeigniter Framework | codesamplez.com says:
    December 20, 2012 at 3:17 am

    […] have already discussed few articles on codeigniter along with codeigniter basics. Codeigniter has good library/mechanism for manipulating database activity. Besides, it introduced […]

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Getting Started With Smarty Template Engine
    Getting Started With Smarty Template Engine
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023