Showing posts with label CodeIgniter. Show all posts

CodeIgniter Basic With CRUD

10:10:00

 

CodeIgniter (CI) is one of popular php framework. If you are already building PHP Application, CodeIgniter will help you to do it better and more easily. With CodeIgniter, you can save time, make your web more robust, your code will be easier to read and maintenance. It is free, lightweight, and simple to install. In this post, we will know more deep about CodeIgniter before write code.
Nice, CodeIgniter is small and lightweight framework. You don’t need long time to download it. You can get it from http://www.codeigniter.com. CI was written by Rick Ellis, rock musician turned programmer.
With CodeIgniter, you can cut down the amount of code you need to type. This is not just good for lazy, but: less type, fewer mistake, and less time for spend debugging.
But, CodeIgniter is not everything. We will not find ‘engine generator’ that can build page self. Several frameworks have features like that. For example, they can create web page (that to do basic Create, Read, Update, and Delete operation) automatically. CodeIgniter doesn’t do this.
This, I copy from their help page: “Our goal for CodeIgniter is maximum performance, capability, and flexibility in the smallest, lightest possible package.
From a technical and architectural standpoint, CodeIgniter was created with the following objectives:

    Dynamic Instantiation. In CodeIgniter, components are loaded and routines executed only when requested, rather than globally. No assumptions are made by the system regarding what may be needed beyond the minimal core resources, so the system is very light-weight by default. The events, as triggered by the HTTP request, and the controllers and views you design will determine what is invoked.
    Loose Coupling. Coupling is the degree to which components of a system rely on each other. The fewer components depend on each other the more reusable and flexible the system becomes. Our goal was a very loosely coupled system.
    Component Singularity. Singularity is the degree to which components have a narrowly focused purpose. In CodeIgniter, each class and its functions are highly autonomous in order to allow maximum usefulness.

Nice feature, CodeIgniter is very flexible. We can apply at PHP 4.3.2 and above, or PHP 5.0 or above. CI support serveral database: MySQL, MySQLi, MS SQL, Postgre, Oracle, SQLite, and ODBC.

Preparing Database

We will learn about showing data from database in CodeIgniter. But, before that, we prepare a database for practice. This post create a database named “ci_test” and a table named “users”. We use phpMyAdmin for easy.

    Open your phpmyadmin.
    Enter database name “ci_test” in create new database field.
    Click Create button. Your database will be created.
    Create new table by running this query in your sql window:

    CREATE TABLE IF NOT EXISTS `users` (

    `id` int(11) NOT NULL AUTO_INCREMENT,

    `name` varchar(50) NOT NULL,

    `email` varchar(100) NOT NULL,

    `address` varchar(255) NOT NULL,

    `mobile` varchar(15) NOT NULL,

    PRIMARY KEY (`id`)

    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;

    Insert some sample data to your users table by running this query in your sql window:


    INSERT INTO `users` (`id`, `name`, `email`, `address`, `mobile`) VALUES

    (1, 'Masud Alam', 'm@sud.com', 'ldsjfla lsdj lsdj flk', '9879879'),

    (2, 'Sohel Alam', 'al@m.com', 'Dhaka,Bangladesh,BD', '09080'),

    (8, 'Salim', 'salim.hossain@ebizzsol.com', 'test', '01717552181'),

    (9, 'Syed Salim', 'salimhossain@gmail.com', 'Gulshan, Dhaka', '01717552181'),

    (10, 'Salim Hossain', 'salimhossain@gmail.com', 'Gazipur-1700, Dhaka, Bangladesh.', '01717552181'),

    (13, 'Galib', 'g@lib.com', 'Dhaka,Bangladesh', '987979');
Showing All Data from your users table:

Now, we learn how to show data in CodeIgniter. As we know, CodeIgniter use MVC pattern. We will use Model for retrieve data from database.

First, build a model. Create a file named “users_model.php” within codeigniter/application/models. Enter following code:

    <?php

    class Users_model extends CI_Model {

    function __construct()

    {

    parent::__construct();

    $this->load->database("ci_test");

    }

    public function get_all_users()

    {

    $query = $this->db->get('users');

    return $query->result();

    }

    }

    ?>

Next, we make a view. Create a file named “show_users.php” within ci/application/views. Enter folowing code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>CI CRUD</title>

    </head>

    <body>

    <h2> Simple CI CRUD Application </h2>

    <table width="600" border="1" cellpadding="5">

    <tr>

    <th scope="col">Id</th>

    <th scope="col">User Name</th>

    <th scope="col">Email</th>

    <th scope="col">Mobile</th>

    <th scope="col">Address</th>

    </tr>

    <?php foreach ($user_list as $u_key){ ?>

    <tr>

    <td><?php echo $u_key->id; ?></td>

    <td><?php echo $u_key->name; ?></td>

    <td><?php echo $u_key->email; ?></td>

    <td><?php echo $u_key->address; ?></td>

    <td><?php echo $u_key->mobile; ?></td>

    </tr>

    <?php }?>

    </table>

    </body>

    </html>

Build controller. Create a file named “users.php” within codeigniter\application\controllers. Enter following code:

    <?php

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

    class Users extends CI_Controller {

    function __construct()

    {

    parent::__construct();

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

    $this->load->model('users_model');

    }

    public function index()

    {

    $data['user_list'] = $this->users_model->get_all_users();

    $this->load->view('show_users', $data);

    }

    }

Now, try to point your browser to http://localhost/codeigniter/index.php/users/

Insert Data to our database using CodeIgniter

Now, we begin create a form for input data.

Create “insert.php” within codeigniter\application\views. Write following code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>CI Insert Form</title>

    </head>

    <body>

    <form method="post" action="<?php echo base_url();?>index.php/users/insert_user_db">

    <table width="400" border="0" cellpadding="5">

    <tr>

    <th width="213" align="right" scope="row">Enter your username</th>

    <td width="161"><input type="text" name="name" size="20" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter your email</th>

    <td><input type="text" name="email" size="20" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter your Mobile</th>

    <td><input type="text" name="mobile" size="20" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter Your Address</th>

    <td><textarea name="address" rows="5" cols="20"></textarea></td>

    </tr>

    <tr>

    <th align="right" scope="row">&nbsp;</th>

    <td><input type="submit" name="submit" value="Send" /></td>

    </tr>

    </table>

    </form>

    </body>

    </html>

Now, we need to load Insert Form. Put at controller (users.php within codeigniter/application/controllers), add_form () method.

    public function add_form()

    {

    $this->load->view('insert');

    }

Now for insert data from our insert.php form to users table we need to create another method called insert_user_db() in our controllers with following code:

    public function insert_new_user()

    {

    $udata['name'] = $this->input->post('name');

    $udata['email'] = $this->input->post('email');

    $udata['address'] = $this->input->post('address');

    $udata['mobile'] = $this->input->post('mobile');

    $res = $this->users_model->insert_users_to_db($udata);

    if($res){

    header('location:'.base_url()."index.php/users/".$this->index());

    }

    }

Now add new method insert_users_to_db in your models
    public function insert_users_to_db($data)

    {

    return $this->db->insert('users', $data);

    }

Now, click your “Insert New User” link in your browser , you see your insert form like this:

CodeIgniter Insert Form

Ok. You can test it. Input some data to your insert form .

CodeIgniter Insert Form with sample data

Now, we create a method called getById() to get a single user information at our model

    public function getById($id){

    $query = $this->db->get_where('users',array('id'=>$id));

    return $query->row_array();

    }

After Create getById Method in our users_model, Now We Create edit Method to send a single user information to edit.php form as follows:

    public function edit(){

    $id = $this->uri->segment(3);

     $data['user'] = $this->users_model->getById($id);

    $this->load->view('edit', $data);

    }

Now we create edit.php form for update users:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>CI Insert Form</title>

    </head>

    <body>

    <form method="post" action="<?php echo base_url();?>index.php/users/update">

    extract($user);

    <table width="400" border="0" cellpadding="5">

    <tr>

    <th width="213" align="right" scope="row">Enter your username</th>

    <td width="161"><input type="text" name="name" size="20" value="<?php echo $name; ?>" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter your email</th>

    <td><input type="text" name="email" size="20" value="<?php echo $email; ?>" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter your Mobile</th>

    <td><input type="text" name="mobile" size="20" value="<?php echo $mobile; ?>" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter Your Address</th>

    <td><textarea name="address" rows="5" cols="20"><?php echo $address; ?></textarea></td>

    </tr>

    <tr>

    <th align="right" scope="row">&nbsp;</th>

    <td>

    <input type="submit" name="submit" value="Update" /></td>

    </tr>

    </table>

    </form>

    </body>

    </html>

After create edit form, now we add updating function.

First, create update_info () method at model “users_model.php”.

    public function update_info($data,$id)

    {

    $this->db->where('users.id',$id);

    return $this->db->update('users', $data);

    }

Then, create update() method at your controller “users.php”:

    public function update()

    {

    $mdata['name']=$_POST['name'];

    $mdata['email']=$_POST['email'];

    $mdata['address']=$_POST['address'];

    $mdata['mobile']=$_POST['mobile'];

    $res=$this->users_model->update_info($mdata, $_POST['id']);

    if($res){

    header('location:'.base_url()."index.php/users/".$this->index());

    }

    }
Deleting Data

Now, we create deleting function.

First, create a method delete_a_user() for deleting data at model.

    public function delete_a_user($id)

    {

    $this->db->where('users.id',$id);

    return $this->db->delete('users');

    }

Then, create a method for deleting data at controller:
view source
print
?

    public function delete($id)

    {

    $this->users_model->delete_a_user($id);

    $this->index();

    }

Read More

5 CodeIgniter libraries you must have

05:02:00


CodeIgniter is a powerful PHP framework with a very small footprint, built for developers who need a simple and elegant toolkit to create full-featured web applications.
There have been multiple reasons why people still stick to CodeIgniter - small footprint, exceptional performance, wonderful documentation, nearly zero configuration and various others. Even I tried to get away from CodeIgniter, but familiarity with the framework brought me back to it again. But, this time I learnt from the shortcomings of the framework and tried to get the best of both the worlds by integrating other third party libraries to vanilla CodeIgniter setup. I have come up with the following list of 5 must have libraries which you should be using if you are developing with CodeIgniter Framework.

HMVC Modular Extension

HMVC stands for Hierarchical model–view–controller. The basic idea is to widgetize your code - turn your code into independent widgets / modules. Once you have your code segregated into modules, it becomes super easy to reuse controllers across other controllers and methods. Another major benefit is code maintenance - if you want to modify a particular feature, you would only need to change code within that particular widget/module and rest of the code remains agnostic to the changes.

The two most commonly used HMVC frameworks are:

Extend your Models

CodeIgniter comes with a wonderful database abstraction layer which supports databases like - MySQL (4.1+), MySQLi, MS SQL, Postgres, Oracle, SQLite, and ODBC. CodeIgniter's Active Record Class makes it very simple to write your database queries independent of your database type. The only downside I felt was that I have to write all the database queries again and again for every model I have. It would really help if we could have a common placeholder for all such common database APIs which can be reused across all the models.
CodeIgniter Base Model is just what I wanted. It comes preloaded with all the basic CRUD (Create Read Update Delete) operations. It has got in built common functions for form validation along with event based observer system such as hook to your callback routine just before inserting data into database. You need to just extend your models from this base model and you are done.

Use a Template Engine

CodeIgniter comes with its own templating engine which can parse simple variables or variable tag pairs. You can use the template library or use the views entirely written in php. Whether to use php for views or use a templating engine is a topic of much debate. Some people like everything in php simply because using that way gives them more flexibility in calling any routine from their code and it lets the view pages run a little faster. However, using templates segregates the presentation logic from business logic so that a front end developer never has to worry about the business logic and can write templates even though he may not understand back-end code. If your website grows bigger and more and more new people join, it becomes easier to expand if you have this segregation of business and presentation logic.
There are way too many options when it comes to templates, but I zeroed down on two template engines specifically for php - Smarty and Twig. They can easily be integrated to CodeIgniter, but there are wonderful people out there who have already done the job for you -

Authentication and Authorization Library

This is where CodeIgniter lags behind other php frameworks. It does not come with an authorization library and you got to build one for yourself. An authentication library provides out of the box support for authenticating users, <authorize the users to do a particular task based on their roles, manage the roles and permissions etc. Once we have any such library, administrative tasks becomes easier and you can segregate the code based on user roles. For example, you would always like to have an admin panel which can only be accessed by site administrator, while all other users should be restricted to access this page. Similarly, a logged in user has the permission to post new blogs, while an usual visitor who is not logged in can just view the blogs. All these tasks become seamless once you use a third party authentication library such as:

Custom Routing Library

Typically there is a one-to-one mapping between a URL component and its corresponding Controller Method. However, CodeIgniter lets you define your own custom routes which can be defined in application/config/routes.php using Regular Expressions and Wildcards. It works well for basic use cases, but if you need more detailed and controlled routes - you got to look out for other alternatives. I haven't found many Custom Routing Libraries as such, but Pigeon is an excellent routing library that supports HTTP method based routing, RESTful and nested routes built on top of native CodeIgniter routing mechanism.
If you find it way too comfortable to sneak peek into php code, then you can check out source code for Bonfire which includes the very best of custom routing library - inherited from Pigeon and Laravel. More details can be found here.

Conclusion

This is by no means a comprehensive list of most useful CodeIgniter libraries, there are many others which you should be using as and when needed. But, this is the very basic set that you should have before starting out development using CodeIgniter.
This is what I feel is the list of 5 CodeIgniter libraries you must have, feel free to leave a comment as to what you think should be your top 5 CodeIgniter library candidtates.

Read More

CodeIgniter Ion Auth User Groups

01:09:00

Introduction

In the previous tutorial, we looked at how to integrate Ion Auth library with CodeIgniter. We also implemented the user authentication system for our CodeIgniter admin panel. This tutorial will pick up from the previous tutorial and add a section that will allow us to create user accounts and user groups. By the end of this tutorial, you should have the following working application.
CodeIgniter Authorization

Topics to be covered

In this tutorial, we will cover the following topics
  • Tutorial pre-requisites
  • Authentication and authorization
  • Ion Auth User Groups Entity Relationship Diagram (ERD)
  • Ion Auth Model
  • Ion Auth Configuration File
  • Tutorial Project Ion Auth User Groups implementation

Tutorial Pre-requisites

This tutorial assumes you are familiar with;
  • PHP basics and Object-oriented programming
  • CodeIgniter Basics
  • You have a web server, PHP and MySQL already configured and running
  • You have a cool IDE i.e. NetBeans IDE, Aptana Studio etc.
  • You have access to a command line/terminal that you can use to run commands
  • You have been following the tutorial series [optional but highly recommended]

Authentication and Authorization

Authentication deals with proving that one is who they claim to be. We handled that in the previous tutorial. Authorization determines whether a user is allowed to access a resource or perform certain operations. This tutorial will handle the authorization aspect of our application.
Ion Auth library implements authorization using user groups. A user group is used to categorize users and allow them to perform certain operations. Ion Auth supports multiple groups. This means a user can belong to more than one group at a time. But for the sake of simplicity, we will assume a user can only belong to a single group at a time.
We will have two user groups namely administrators and members. Administrators will be able to create and update users and user groups. Members will not be able to access the users and user groups data or perform any operations.
This will be implemented in two easy steps;
  1. We will hide the links to user groups and users in the admin panel navigation links
  2. In case the user knows the URL and types it directly, we will check if they have access rights to it and redirect them to the dashboard if they do not access.

Ion Auth Users Groups Entity Relationship Diagram (ERD)

The following diagram shows the Ion Auth users groups ERD diagram
Ion Auth ERD
The relationship between the users and groups tables is many to many. This is implemented by introducing the intermediate table users_groups that links the two tables using the user_id and group_id fields.

Ion Auth Model

Ion Auth model ships with its own model that handles all database interactions for us. It is possible to create our own models but for the sake of simplicity we will stick with the Ion Auth model. The model is location in the directory /application/models/ion_auth_model.php. I don’t recommend changing anything in the model for the sake of this tutorial. We will leave the model as it is.

Ion Auth Configuration File

One of the things that I love about Ion Auth is its flexibility. Ion Auth ships with a configuration file that is located in /application/config/ion_auth.php.
The configuration file can be used to;
  • Set the unique identify – the default is email field
  • Set table users – the default tables names are users, groups and users_groups. You can change the table names if you have to but we will stick with defaults in this tutotial
  • Password minimum and maximum lengths
  • And many more… you can explore the various options available
For the sake of simplicity, we will work with default settings that ship with Ion Auth.

Tutorial Project Ion Auth User Groups implementation

Let’s now get our hands dirty. We will start with the controllers then create missing views and update some of the existing views

Admin_Controller

All admin controllers are extending the class Admin_Controller. Open the file located in /application/libraries/Admin_Controller.php
Update the code to the following
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Admin_Controller extends MY_Controller {
    public $is_admin;
    public $logged_in_name;

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

        // Set container variable
        $this->_container = $this->config->item('ci_my_admin_template_dir_admin') . "layout.php";
        $this->_modules = $this->config->item('modules_locations');

        $this->load->library(array('ion_auth'));

        if (!$this->ion_auth->logged_in()) {
            redirect('/auth', 'refresh');
        }

        $this->is_admin = $this->ion_auth->is_admin();
        $user = $this->ion_auth->user()->row();
        $this->logged_in_name = $user->first_name;

        log_message('debug', 'CI My Admin : Admin_Controller class loaded');
    }
}
HERE,
  • public $is_admin; defines a variable that determines whether the user is an admin or not
  • public $logged_in_name; defines a variable that contains the name of the user who is currently logged in
  • $this->load->library(array('ion_auth')); loads the Ion Auth library
  • if (!$this->ion_auth->logged_in()) {…} redirects the user to the home page if they are not logged in
  • $this->is_admin = $this->ion_auth->is_admin(); stores the admin status of the user into the the variable is_admin
  • $user = $this->ion_auth->user()->row(); retrieves the user object of the currently logged in user
  • $this->logged_in_name = $user->first_name; populates the variable logged_in_name with the first name of the logged in user

UserGroups Controller

Create a new controller in /application/modules/admin/UserGroups.php
Add the following code

<?php

class UserGroups extends Admin_Controller {

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

        $group = 'admin';

        if (!$this->ion_auth->in_group($group))
        {
            $this->session->set_flashdata('message', 'You must be an administrator to view the user groups page.');
            redirect('admin/dashboard');
        }
    }

    public function index() {    
        $groups = $this->ion_auth->groups()->result();

        $data['groups'] = $groups;
        $data['page'] = $this->config->item('ci_my_admin_template_dir_admin') . "groups_list";
        $this->load->view($this->_container, $data);
    }

    public function create() {
        if ($this->input->post('name')) {
            $name = $this->input->post('name');
            $description = $this->input->post('description');

            $group = $this->ion_auth->create_group($name,$description);

            if(!$group)
            {
                $view_errors = $this->ion_auth->messages();
            }
            else
            {
                redirect('/admin/user-groups', 'refresh');
            }
        }
        $data['page'] = $this->config->item('ci_my_admin_template_dir_admin') . "groups_create";
        $this->load->view($this->_container, $data);
    }

    public function edit($id) {
        if ($this->input->post('name')) {
            $name = $this->input->post('name');
            $description = $this->input->post('description');

            $group_update = $this->ion_auth->update_group($id, $name, $description);

            redirect('/admin/user-groups', 'refresh');
        }

        $group =  $this->ion_auth->group($id)->row();

        $data['group'] = $group;
        $data['page'] = $this->config->item('ci_my_admin_template_dir_admin') . "groups_edit";
        $this->load->view($this->_container, $data);
    }

    public function delete($id) {
        $group_delete = $this->ion_auth->delete_group($id);

        redirect('/admin/user-groups', 'refresh');
    }
}
HERE,
  • $group = 'admin'; defines the allowed user group by name
  • if (!$this->ion_auth->in_group($group)){…} checks if the current logged in user belongs to the admin group. If yes access is grated. If it is not, the user is redirected to the dashboard. This code is placed in the __constructor so that it is applicable to all the methods in the class.
  • $groups = $this->ion_auth->groups()->result(); retrieves all groups as an object array
  • $group = $this->ion_auth->create_group($name,$description); creates a new group
  • $group_update = $this->ion_auth->update_group($id, $name, $description); updates an existing group
  • $group_delete = $this->ion_auth->delete_group($id); deletes an existing group

Users Controller

Create a new controller in /application/modules/admin/Users.php
Add the following code

<?php

class Users extends Admin_Controller {

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

        $group = 'admin';

        if (!$this->ion_auth->in_group($group))
        {
            $this->session->set_flashdata('message', 'You must be an administrator to view the users page.');
            redirect('admin/dashboard');
        }
    }

    public function index() {    
        $users = $this->ion_auth->users()->result();

        $data['users'] = $users;
        $data['page'] = $this->config->item('ci_my_admin_template_dir_admin') . "users_list";
        $this->load->view($this->_container, $data);
    }

    public function create() {
        if ($this->input->post('username')) {
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $email = $this->input->post('email');
            $group_id = array( $this->input->post('group_id'));

            $additional_data = array(
                'first_name' => $this->input->post('first_name'),
                'last_name' => $this->input->post('last_name'),
                'username' => $this->input->post('username'),
                'phone' => $this->input->post('phone'),
            );

            $user = $this->ion_auth->register($email, $password, $email, $additional_data,$group_id);

            if(!$user)
            {
                $errors = $this->ion_auth->errors();
                echo $errors;
                die('done');
            }
            else
            {
                redirect('/admin/users', 'refresh');
            }


        }

        $data['groups'] = $this->ion_auth->groups()->result();
        $data['page'] = $this->config->item('ci_my_admin_template_dir_admin') . "users_create";
        $this->load->view($this->_container, $data);
    }

    public function edit($id) {
        if ($this->input->post('first_name')) {
            $data['first_name'] = $this->input->post('first_name');
            $data['last_name'] = $this->input->post('last_name');
            $data['email'] = $this->input->post('email');
            $data['phone'] = $this->input->post('phone');
            $group_id = $this->input->post('group_id');

            $this->ion_auth->remove_from_group('', $id);
            $this->ion_auth->add_to_group($group_id, $id);

            $this->ion_auth->update($id, $data);

            redirect('/admin/users', 'refresh');
        }

        $this->load->helper('ui');

        $data['groups'] = $this->ion_auth->groups()->result();
        $data['user'] = $this->ion_auth->user($id)->row();
        $data['user_group'] = $this->ion_auth->get_users_groups($id)->row();
        $data['page'] = $this->config->item('ci_my_admin_template_dir_admin') . "users_edit";
        $this->load->view($this->_container, $data);
    }

    public function delete($id) {
        $this->ion_auth->delete_user($id);

        redirect('/admin/users', 'refresh');
    }
}
HERE,
  • $group = 'admin'; defines the allowed user group by name
  • if (!$this->ion_auth->in_group($group)){…} checks if the current logged in user belongs to the admin group. If yes access is grated. If it is not, the user is redirected to the dashboard. This code is placed in the __constructor so that it is applicable to all the methods in the class.
  • $users = $this->ion_auth->users()->result(); retrieves all users as an object array
  • $user = $this->ion_auth->register($email, $password, $email, $additional_data,$group_id); creates a new user. The first parameter $email is the identity column, it is followed by the $password field which Ion Auth will encrypt for us. The third parameter $email is the email field value. $additional_data contains additional data such as firstname, lastname phone etc. $group_id specifies the group id. If no value is specified, Ion Auth will use the default value that is specified in the Ion configuration file.
  • $this->ion_auth->update($id, $data); updates an existing user. Unfortunately, we cannot pass the group ids when updating a user. We instead used a hack to accomplish that. $this->ion_auth->remove_from_group('', $id); removes the existing user from all groups. $this->ion_auth->add_to_group($group_id, $id); adds a the updated user group.
  • $this->ion_auth->delete_user($id); deletes an existing user and all groups associated with the user.

Users and Groups views

Let’s now create the following views in /application/modules/admin/views/themes/default 1. groups_create.php 2. groups_edit.php 3. groups_list.php 4. users_create.php 5. users_edit.php 6. users_list.php
For the sake of simplicity, we will not include the code for the views in the tutorial. Download the attached tutorial files and replace the above files. The code is for views is pretty standard. Use the comments section to ask if you have any questions.
Next we will need to update the header view located in /application/views/admin/themes/default/header.php. Replace the header.php with the file from the downloaded tutorial file. Replace the file /application/modules/admin/views/themes/default/dashboard.php with the one that you downloaded.

Testing the authorization

Login as an administrator
The admin panel should now appear as follows
CodeIgniter Authorization
You can view the user groups, edit and add new ones if you want. Note: Don’t delete the default groups. We need them in this tutorial.
Using the users link, create a new user and put members as the group
Login using the new user that you created
You will get results similar to the following
CodeIgniter Authorization
Try to access the following URL directly

http://localhost/ci-my-admin/admin/users/
You will get the following message
CodeIgniter Authorization

Summary

Managing authorization using Ion Auth is very simple and straight forward. The library has most functionality that you need out of the box. It is also very flexible and can be configured to suit your requirements via the configuration file.

Read More