Skip to content

Instantly share code, notes, and snippets.

@noncent
Last active July 11, 2017 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noncent/73fc5c859bad631e6de9cbb3a4b90098 to your computer and use it in GitHub Desktop.
Save noncent/73fc5c859bad631e6de9cbb3a4b90098 to your computer and use it in GitHub Desktop.

Here is the very simple demo for getting user's data from database and login system. I hope you will enjoy the code and comments :)

Just get it step by step, Do not hurry

.htaccess code: (Place inside your CodeIgniter project)

<IfModule mod_rewrite.c>

    # Make sure directory listing is disabled
	Options +FollowSymLinks -Indexes
	RewriteEngine on

	# NOTICE: If you get a 404 play with combinations of the following commented out lines
	#AllowOverride All
	#RewriteBase /wherever/codeginiter/is

	# Restrict your site to only one domain
	# !important USE ONLY ONE OPTION

	# Option 1: To rewrite "www.domain.com -> domain.com" uncomment the following lines.
	#RewriteCond %{HTTPS} !=on
	#RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
	#RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

	# Option 2: To rewrite "domain.com -> www.domain.com" uncomment the following lines.
	#RewriteCond %{HTTPS} !=on
	#RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
	#RewriteCond %{HTTP_HOST} (.+)$ [NC]
	#RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]

	# Remove index.php from URL
	#RewriteCond %{HTTP:X-Requested-With}	!^XMLHttpRequest$
	#RewriteCond %{THE_REQUEST}				^[^/]*/index\.php [NC]
	#RewriteRule ^index\.php(.*)$			$1 [R=301,NS,L]

	# Keep people out of codeigniter directory and Git/Mercurial data
	# RedirectMatch 403 ^/(system|\.git|\.hg).*$

	# Send request via index.php (again, not if its a real file or folder)
	RewriteCond %{REQUEST_FILENAME} !-f
	RewriteCond %{REQUEST_FILENAME} !-d

	<IfModule mod_php5.c>
		RewriteRule ^(.*)$ index.php/$1 [L]
	</IfModule>

	<IfModule !mod_php5.c>
		RewriteRule ^(.*)$ index.php?/$1 [L]
	</IfModule>

</IfModule>

index.php (Place below code just after)

`define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');`
    /**
     * Define By Neeraj Singh
     *
     * Automatic base url
     */
    define('APP_URL', ($_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . "://{$_SERVER['SERVER_NAME']}".str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']));

config/autoload.php

    /*
    | -------------------------------------------------------------------
    |  Auto-load Libraries
    | -------------------------------------------------------------------
    | These are the classes located in system/libraries/ or your
    | application/libraries/ directory, with the addition of the
    | 'database' library, which is somewhat of a special case.
    |
    | Prototype:
    |
    |	$autoload['libraries'] = array('database', 'email', 'session');
    |
    | You can also supply an alternative library name to be assigned
    | in the controller:
    |
    |	$autoload['libraries'] = array('user_agent' => 'ua');
    */
    $autoload['libraries'] = array('database','session','user_agent','form_validation');
    
    /*
    | -------------------------------------------------------------------
    |  Auto-load Helper Files
    | -------------------------------------------------------------------
    | Prototype:
    |
    |	$autoload['helper'] = array('url', 'file');
    */
    $autoload['helper'] = array('html', 'url', 'form', 'cookie', 'security');

config/routes.php

    $route['default_controller'] = 'users';

config/config.php

    /*
    |--------------------------------------------------------------------------
    | Base Site URL
    |--------------------------------------------------------------------------
    |
    | URL to your CodeIgniter root. Typically this will be your base URL,
    | WITH a trailing slash:
    |
    |	http://example.com/
    |
    | WARNING: You MUST set this value!
    |
    | If it is not set, then CodeIgniter will try guess the protocol and path
    | your installation, but due to security concerns the hostname will be set
    | to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
    | The auto-detection mechanism exists only for convenience during
    | development and MUST NOT be used in production!
    |
    | If you need to allow multiple domains, remember that this file is still
    | a PHP script and you can easily do that on your own.
    |
    */
    $config['base_url'] = APP_URL;
    
    /*
    |--------------------------------------------------------------------------
    | Index File
    |--------------------------------------------------------------------------
    |
    | Typically this will be your index.php file, unless you've renamed it to
    | something else. If you are using mod_rewrite to remove the page set this
    | variable so that it is blank.
    |
    */
    $config['index_page'] = '';
    
    /*
    |--------------------------------------------------------------------------
    | Encryption Key
    |--------------------------------------------------------------------------
    |
    | If you use the Encryption class, you must set an encryption key.
    | See the user guide for more info.
    |
    | https://codeigniter.com/user_guide/libraries/encryption.html
    |
    */
    $config['encryption_key'] = 'iT58EbmAQnBjvf7ZYwVxgMqXHhaeC6s2Ny93utcp';
    
    /*
    |--------------------------------------------------------------------------
    | Session Variables
    |--------------------------------------------------------------------------
    |
    | 'sess_driver'
    |
    |    The storage driver to use: files, database, redis, memcached
    |
    | 'sess_cookie_name'
    |
    |    The session cookie name, must contain only [0-9a-z_-] characters
    |
    | 'sess_expiration'
    |
    |    The number of SECONDS you want the session to last.
    |    Setting to 0 (zero) means expire when the browser is closed.
    |
    | 'sess_save_path'
    |
    |    The location to save sessions to, driver dependent.
    |
    |    For the 'files' driver, it's a path to a writable directory.
    |    WARNING: Only absolute paths are supported!
    |
    |    For the 'database' driver, it's a table name.
    |    Please read up the manual for the format with other session drivers.
    |
    |    IMPORTANT: You are REQUIRED to set a valid save path!
    |
    | 'sess_match_ip'
    |
    |    Whether to match the user's IP address when reading the session data.
    |
    |    WARNING: If you're using the database driver, don't forget to update
    |             your session table's PRIMARY KEY when changing this setting.
    |
    | 'sess_time_to_update'
    |
    |    How many seconds between CI regenerating the session ID.
    |
    | 'sess_regenerate_destroy'
    |
    |    Whether to destroy session data associated with the old session ID
    |    when auto-regenerating the session ID. When set to FALSE, the data
    |    will be later deleted by the garbage collector.
    |
    | Other session cookie settings are shared with the rest of the application,
    | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
    |
     */
    $config['sess_cookie_name']        = 'ci_session';
    $config['sess_save_path']          = null;
    $config['sess_regenerate_destroy'] = false;
    $config['sess_expiration']         = 0;
    $config['sess_expire_on_close']    = true;
    $config['sess_encrypt_cookie']     = false;
    $config['sess_use_database']       = true;
    $config['sess_driver']             = 'database';
    $config['sess_table_name']         = 'ci_sessions';
    $config['sess_match_ip']           = false;
    $config['sess_match_useragent']    = false;
    $config['sess_time_to_update']     = 300;

ci_sessions mysql table:

    DROP TABLE IF EXISTS `ci_sessions`;
    
    CREATE TABLE `ci_sessions` (
      `id` varchar(40) NOT NULL,
      `ip_address` varchar(45) NOT NULL,
      `timestamp` int(10) unsigned NOT NULL DEFAULT '0',
      `data` blob NOT NULL,
      PRIMARY KEY (`id`),
      KEY `ci_sessions_timestamp` (`timestamp`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

mysql table users (PASSWORD is 'password'):

    /*Table structure for table `users` */
    
    DROP TABLE IF EXISTS `users`;
    
    CREATE TABLE `users` (
      `uid` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(25) DEFAULT NULL,
      `password` varchar(55) DEFAULT NULL,
      `first_name` varchar(25) DEFAULT NULL,
      `email` varchar(25) DEFAULT NULL,
      `phone_number` varchar(10) DEFAULT NULL,
      `status` enum('0','1') DEFAULT '0',
      `date_created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`uid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    
    /*Data for the table `users` */
    
    insert  into `users`(`uid`,`username`,`password`,`first_name`,`email`,`phone_number`,`status`,`date_created`) values 
    (1,'scott','5f4dcc3b5aa765d61d8327deb882cf99','Scott','scott.dimon@example.com','1234567890','1','2017-07-10 22:45:20'),
    (2,'mikey','5f4dcc3b5aa765d61d8327deb882cf99','Mikey','mikey.logan@email.com','3214521412','1','2017-07-10 22:46:14');

Users Controller:

    <?php
    // security first
    defined('BASEPATH') or exit('No direct script access allowed');
    /**
     * Class User to handle all login and user's related actions
     */
    class Users extends CI_Controller
    {
        /**
         * [__construct description]
         */
        public function __construct()
        {
            // call parent constructor
            parent::__construct();
            // load Users_model as user_model alias
            $this->load->model('Users_model', 'user_model');
        }
        /**
         * Index Page for this controller.
         *
         * Maps to the following URL
         *         http://example.com/index.php/users
         *    - or -
         *         http://example.com/index.php/users/index
         *    - or -
         * Since this controller is set as the default controller in
         * config/routes.php, it's displayed at http://example.com/
         *
         * So any other public methods not prefixed with an underscore will
         * map to /index.php/users/<method_name>
         * @see https://codeigniter.com/user_guide/general/urls.html
         */
        public function index()
        {
            // check if user already login and session set
            if ($this->session->userdata('user_data')['logged_in']) {
                // redirect on post page
                redirect('posts');
            } else {
                // else show login page
                $this->login();
            }
        }
        /**
         * [login description]
         * @return [type] [description]
         */
        public function login()
        {
            if ($this->input->post()) {
                $data = array();
                // validate user name
                $this->form_validation->set_rules('username', 'Username', 'required');
                // validate user's password
                $this->form_validation->set_rules('password', 'Password', 'required');
                // chek if validation error
                if ($this->form_validation->run() === false) {
                    // show again login page
                    $this->load->view('templates/header');
                    $this->load->view('users/login', $data);
                    $this->load->view('templates/footer');
                } else {
                    // fetching user
                    $username = $this->input->post('username', true);
                    // Encrypted password
                    $password = md5($this->input->post('password', true));
                    //login user
                    $result = $this->user_model->login($username, $password);
                    // if no false
                    if ($result) {
                        //creating session
                        $user_data = array(
                            'user_id'      => $result->uid,
                            'username'     => $result->username,
                            'email'        => $result->email,
                            'phone_number' => $result->phone_number,
                            'first_name'   => $result->first_name,
                            'logged_in'    => true
                        );
                        $this->session->set_userdata('user_data', $user_data);
                        // Set message to be sent
                        $this->session->set_flashdata('user_login', 'Welcome');
                        // redirect on post page
                        redirect('posts');
                    } else {
                        // Set message to be sent
                        $this->session->set_flashdata('login_fail', 'Login Failed');
                        // redirect on login page again
                        redirect('users/login');
                    }
                }
            } else {
                // show again login page
                $this->load->view('templates/header');
                $this->load->view('users/login');
                $this->load->view('templates/footer');
            }
        }
        /**
         * [get_user description]
         * @return [type] [description]
         */
        public function get_user()
        {
            // if user login
            if ($this->session->userdata('user_data')['logged_in']) {
                $data     = array();
                $username = $this->session->userdata('user_data')['username'];
                // send user id and get data
                $data = $this->user_model->get_user($this->session->userdata('user_data')['user_id']);
                // if object
                if ($data) {
                    // strip 0 index
                    $data = array_shift($data);
                }
                // print_r($data); die;
                // Array
                // (
                //     [uid] => 1
                //     [email] => scott.dimon@example.com
                //     [username] => scott
                //     [phone_number] => 1234567890
                //     [first_name] => Scott
                // )
                $this->load->view('templates/header');
                $this->load->view('posts/post', array('result' => $data));
                $this->load->view('templates/footer');
            }
        }
        /**
         * [logout description]
         * @return [type] [description]
         */
        public function logout()
        {
            // flush the all session
            $this->session->sess_destroy();
            // redirect on login page
            redirect('users/login');
        }
    }
    /* End of file Users.php */
    /* Location: ./application/controllers/Users.php */

Posts Controller:

    <?php
    // security, security....
    (defined('BASEPATH') or exit('No direct script access allowed'));
    /**
     * Class Posts
     */
    class Posts extends CI_Controller
    {   
        /**
         * [__construct description]
         */
        public function __construct()
        {
            parent::__construct();
        }
        /**
         * [index description]
         * @return [type] [description]
         */
        public function index()
        {
            // check if user already login and session set
            if ($this->session->userdata('user_data')['logged_in']) {
                $data = array(
                    // get user name
                    'name'         => $this->session->userdata('user_data')['first_name'],
                    // get user email
                    'email'        => $this->session->userdata('user_data')['email'],
                    // get user phone number
                    'phone_number' => $this->session->userdata('user_data')['phone_number']
                );
                // show post page header
                $this->load->view('templates/header');
                // send user data as array in view
                $this->load->view('posts/post', $data);
                // show post page footer
                $this->load->view('templates/footer');
            } else {
                // get loss in user login page
                redirect('users/login');
            }
        }
    }
    /* End of file Posts.php */
    /* Location: ./application/controllers/Posts.php */

Users Model:

    <?php
    (defined('BASEPATH') or exit('No direct script access allowed'));
    /**
     * Class Users Model to intact with user table
     */
    class Users_model extends CI_Model
    {
        /**
         * MySQL table
         * @var string
         */
        private $table = 'users';
        /**
         * [__construct description]
         */
        public function __construct()
        {
            parent::__construct();
        }
        /**
         * [login description]
         * @param  [type] $username [description]
         * @param  [type] $password [description]
         * @return [type]           [description]
         */
        public function login($username, $password)
        {
            // select table columns
            $this->db->select('uid, email, username, phone_number, first_name');
            // where user name
            $this->db->where('username', $username);
            // where password
            $this->db->where('password', $password);
            // and status = 1
            $this->db->where('status', '1');
            // from user table
            $result = $this->db->get($this->table);
            // if rows returns
            if ($result->num_rows() === 1) {
                // return all rows as object
                return $result->row();
            } else {
                // no result
                return false;
            }
        }
        /**
         * [get_user description]
         * @param  [type] $uid [description]
         * @return [type]      [description]
         */
        public function get_user($uid = null)
        {
            // if user id pass by user
            if (!is_null($uid)) {
                // select table columns
                $this->db->select('uid, email, username, phone_number, first_name');
                // get records by user id
                $this->db->where('uid', $uid);
                // from user table
                $query = $this->db->get($this->table);
            }
            // else user login then get user id from session
            else if ($this->session->userdata('user_data')['logged_in']) {
                // select table columns
                $this->db->select('uid, email, username, phone_number, first_name');
                // user session user id
                $this->db->where('uid', $this->session->userdata('user_data')['user_id']);
                // from user table
                $query = $this->db->get($this->table);
            } else {
                return false;
            }
            // if record exists
            if ($query->num_rows() > 0) {
                // return stdClass Object
                return $query->result_array();
            } else {
                return false;
            }
        }
    }
    /* End of file Users_model.php */
    /* Location: ./application/models/Users_model.php */

Views/templates/header.php:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="robots" content="noindex, nofollow">
        <title>Login in panel - Bootsnipp.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">    
        <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
    </head>
    <body>

Views/templates/footer.php:

    </body>
    </html>

Views/users/login.php:

    <div class="container">       
      <div id="loginbox" style="margin-top:50px;" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">                    
        <div class="panel panel-info" >
          <div class="panel-heading">
            <div class="panel-title">Sign In</div>                        
          </div>     
          <div style="padding-top:30px" class="panel-body" >
            
            <?php // when wrong user name or password or form validation ?>
            <?php if (validation_errors() || $this->session->flashdata('login_fail')) : ?>
              <div id="login-alert" class="alert alert-danger col-sm-12">
    
                <!-- Form Validation  -->
                <?php echo validation_errors(); ?>
                <!-- Form Validation  -->
    
                <!-- Flash Message -->
                <?php if($this->session->flashdata('login_fail')) :?>
                  <?=$this->session->flashdata('login_fail')?>
                <?php endif;?> 
                <!-- Flash Message -->
                
              </div>
            <?php endif; ?>
    
            <form id="loginform" class="form-horizontal" role="form" method="post" action="<?=base_url('users/login')?>">
              <div style="margin-bottom: 25px" class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                <input id="login-username" type="text" class="form-control" name="username" value="" placeholder="Username">                                        
              </div>
              <div style="margin-bottom: 25px" class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                <input id="login-password" type="password" class="form-control" name="password" placeholder="Password">
              </div>
              <div style="margin-top:10px" class="form-group">
                <!-- Button -->
                <div class="col-sm-12 controls">
                  <input type="submit" value="Login" class="btn btn-success">
                </div>
              </div>
            </form>     
          </div>                     
        </div>  
      </div>
    </div>

Views/posts/post.php:

    <div class="container-full">
        <div class="navbar navbar-default">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">Brand</a>
            </div>
            <ul class="nav navbar-nav">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#">Link</a></li>
                <li><a href="#">Link</a></li>
                <li class="divider-vertical"></li>
                <li><a href="#">More</a></li>
                <li><a href="#">Options</a></li>
            </ul>
        </div>
        <div class="jumbotron text-center">
            <h1>
                <?php if($this->session->flashdata('user_login')) :?>
                    <?=$this->session->flashdata('user_login')?>
                <?php endif;?>                        
            </h1>
            <p class="lead">
                <?php if($this->session->userdata('user_data')) :?>
                    Hello!, <?=$this->session->userdata('user_data')['first_name']?>. Shall we communicate via <?=$this->session->userdata('user_data')['email']?> or <?=$this->session->userdata('user_data')['phone_number']?>
                <?php endif;?>   
            </p>
            <p><a class="btn btn-large btn-success" href="<?=base_url('users/logout')?>" target="ext">Log Out</a></p>
        </div>
        <div class="rows">
            <!-- user Information -->
            <?php if(isset($result) && is_array($result)): ?>
                <table class="table table-striped text-left">
                    <thead>
                        <?php echo '<tr><th>',implode('</th><th>', array_keys($result)), '</th></tr>';?>
                    </thead>
                    <tbody>
                        <?php echo '<tr><td>',implode('</td><td>', array_values($result)), '</td></tr>';?>                   
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
    <!-- /container full -->

Done!,

Why I am doing this.. ? I Love CodeIgniter and wanna help every one who want to learn or work in CodeIgniter... :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment