Tuesday, March 12, 2013

CodeIgniter Login Tutorial

Leave a Comment
CodeIgniter Login in Mobile View
CodeIgniter Login
CodeIgniter Login System Tutorial - Pada kesempatan kali ini saya akan coba membahas tentang bagaimana membuat sistem login dan register account dengan menggunakan framework CodeIgniter, MySQL sebagai database servernya dan Twitter Bootstrap untuk user interface nya. CodeIgniter merupakan PHP framework yang cukup mudah untuk dipelajari dan juga mendukung konsep MVC (Model View Controller). Tutorial ini juga membahas sedikit tentang bagaimana mudahnya membuat GUI (front-end) dengan menggunakan Twitter Bootstrap.

Twitter Bootsrap merupakan sebuah framework yang cukup populer juga saat ini yang dibangun oleh mantan web designer Twitter @mdo dan @fat. Fitur dan komponen Twitter Bootstrap cukup lengkap dengan berbagai animasi yg menarik, kita dapat menggunakan jQuery untuk animasi ataupun dengan html markup yang sudah disediakan. Selain itu, kita tidak perlu lagi membangun web dengan dua versi, versi desktop atau versi mobile, karena Twitter Bootstrap dilengkapi dengan fitur responsive design, kita hanya perlu memodifikasi css dengan mendefinisikan style CSS berdasarkan lebarnya resolusi layar. Thumbnail diatas adalah screenshoot aplikasi pada tutorial ini yg dijalankan di iPhone.

Fitur aplikasi yang akan dibangun :
  • Proses login ke sistem (memanfaatkan CI Session dan Library Form Validation).
  • Proses pendaftaran akun (register / create account).
  • Lihat data akun detail.
Berikut merupakan hasil akhir versi desktop-nya :
CodeIgniter Login Tutorial
CodeIgniter Login - Login and Register Form

Persiapan

Database

Hal yang pertama dilakukan adalah membuat basis data (database) dengan MySQL, masuk ke phpMyAdmin, input SQL sintax dibawah ini pada menu SQLquery atau sintax pada phpMyAdmin :
CREATE DATABASE `ci-login` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

USE `ci-login`;

CREATE TABLE IF NOT EXISTS `account` (
  `first_name` varchar(30) NOT NULL,
  `last_name` varchar(30) NOT NULL,
  `email_address` text NOT NULL,
  `username` varchar(30) NOT NULL,
  `password` text NOT NULL,
  PRIMARY KEY  (`username`)
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;

INSERT INTO `account` (`first_name`, `last_name`, `email_address`, `username`, `password`) VALUES
('Aditya', 'Nursyahbani', '[email protected]', 'admin', '21232f297a57a5a743894a0e4a801fc3');
Alternatif lain, anda juga dapat melakukan fungsi import phpMyAdmin dari hasil dumping file ci-login.sql yg terdapat di source code aplikasi ini. Setting konfigurasi CodeIgniter (config.php, autoload.php, database.php, route.php). Setting base_url dan encryption_key untuk dapat menggunakan CodeIgniter Session, untuk lebih jelas bisa di lihat di tutorial sebelumnya membuat captcha dengan CodeIgniter

Model

Model merepresentasikan bagaimana operasi / perintah-perintah terhadap suatu basis data yang umumnya terdiri dari CRUD (Create Read Update Delete) operation. Pada tutorial kali ini kita hanya menggunakan satu model dengan nama account_model.php yang terdiri dari fungsi validasi login, membuat akun baru dan untuk melihat akun detail. Buat file account_model.php (application/models) yang isinya sebagai berikut :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Account_model extends CI_Model {
  private $table_name = 'account';
  private $pk = 'username';
  
  public function validasi() {
    $this->db->where('username', $this->input->post('username'));
    $this->db->where('password', md5($this->input->post('password')));
    $query = $this->db->get($this->table_name);
    if($query->num_rows == 1) {
      return true;
    }
  }
  
  public function buat_akun() {
    $data_baru = array(   
      'first_name'    => $this->input->post('fname'),
      'last_name'     => $this->input->post('lname'),
      'email_address' => $this->input->post('email'),
      'username'      => $this->input->post('uname'),
      'password'      => md5($this->input->post('pass'))
    );    
    $simpan_data = $this->db->insert($this->table_name, $data_baru);
    return $simpan_data;
  }
  
  public function lihat_data($username){
    $query = $this->db->get_where($this->table_name, array($this->pk => $username));
    return $query->row_array(); 
  }
}
/* End of file account_model.php */
/* Location: ./application/models/account_model.php */

Controller

Controller merupakan mediator antara Model dan View dalam konsep MVC dimana semua request/response di handle oleh controller. Misal user melakukan login yg diakses dari form login (View) -> Controller menerima request dan mengeksekusi fungsi cek login, jika data form yang di submit lengkap, Controller memanggil fungsi validasi pada Model dan Model akan mengecek form yang di submit dengan data yang ada pada database kemudian memberikan nilai kembalian berupa TRUE atau FALSE, pada akhirnya Controller memberikan response kepada user (View). Pada tutorial ini kita akan membuat 2 Controller (application/controllers), login dan user Controller. Controller login menghandle fungsi untuk validasi login, membuat akun dan fungsi logout sedangkan Controller user menghandle fungsi untuk melihat detail akun dan pada saat controller ini di inisialisasi akan menjalankan fungsi pengecekan session yang aktif.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

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

  public function index(){
    $data['content'] = 'login';
    $this->load->view('template/index', $data);
  }
  
  public function cek_login(){
    $user = $this->input->post('username');
    $pass = $this->input->post('password');
 
    if(empty($user) or empty($pass)){
      $this->session->set_flashdata('msg', 'Username or password can\'t be blank');
      redirect('login');
    }
 
    $query = $this->account_model->validasi();
    if($query){
      $data = array(
        'username' => $user,
        'is_logged_in' => true   
      );
 
      $this->session->set_userdata($data);
      redirect('user');
    }else{
      $this->session->set_flashdata('msg', 'Invalid username and password');
      redirect('login');
    }
  }
  
  public function signup(){
    $this->load->library('form_validation');
    $this->form_validation->set_rules('fname', 'First Name', 'trim|required');
    $this->form_validation->set_rules('lname', 'Last Name', 'trim|required');
    $this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email');
    $this->form_validation->set_rules('uname', 'Username', 'trim|required|min_length[4]');
    $this->form_validation->set_rules('pass', 'Password', 'trim|required|min_length[6]|max_length[16]');
    $this->form_validation->set_rules('repass', 'Re-Password', 'trim|required|matches[pass]');
 
    if($this->form_validation->run() == FALSE){
      $data['content'] = 'login';
      $this->load->view('template/index', $data);
    }else{
      if($query = $this->account_model->buat_akun()){
        $this->session->set_flashdata('success', 'Your account successfully created! you can login now');
        redirect('login');
      }else{
        $this->session->set_flashdata('msg', 'Error insert database');
        redirect('login');
      }
    }
  }
  
  public function logout(){
    $this->session->sess_destroy();
    $this->index();
  }
}
/* End of file login.php */
/* Location: ./application/controllers/login.php */
  • Line 5-8 Memanggil / load account_model pada saat inisialisasi controller.
  • Line 10-13 Menampilkan form login/register ketika tidak ada request method atau fungsi pada controller.
  • Line 15-37 Fungsi untuk validasi login, jika username atau password kosong akan dikembalikan ke form login dengan pesan error, jika lengkap akan dicocokkan dengan data yang ada pada database. Jika hasilnya cocok maka, 2 sesi / session yang akan di daftarkan, sesi dengan nama username yang menampung nama user yang login dan sesi dengan nama is_logged_in yang diisi dengan nilai true dan akan di arahkan ke controller user.
  • Line 39-60 Fungsi untuk pendaftaran akun baru yang didalamnya terdapat perintah untuk validasi form input. jika input valid maka data akan di simpan pada database, jika invalid akan muncul pesan error.
  • Line 62-65 Fungsi untuk logout akun, sesi user yang aktif akan dihapus / dihancurkan dan redireksi ke halaman login.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller{
  
  public function __construct(){
    parent::__construct();
    $this->is_logged_in(); 
  }
  
  public function index(){
    $data['content'] = 'user_area';
    $this->load->view('template/index', $data);
  }
  
  public function view_account(){
    $this->load->model('account_model');
    $data['account'] = $this->account_model->lihat_data($this->session->userdata('username'));
    $data['content'] = 'user_detail';
    $this->load->view('template/index', $data);
  }  
  
  public function is_logged_in(){
    $is_logged_in = $this->session->userdata('is_logged_in');
    if(!isset($is_logged_in) || $is_logged_in != true){
      $this->session->set_flashdata('msg', 'Access denied! You don\'t have permission to access this page or session has expired. Please use login form!');
      redirect('login');
    }
  }
}
/* End of file user.php */
/* Location: ./application/controllers/user.php */

View

View merupakan antar muka atau tampilan (Graphical User Interface) yang akan berinteraksi langsung dengan end user. Tutorial ini akan menggunakan view yang dinamis (di generate dari template) karena halaman yang statis seperti header, footer dan script akan dipanggil berulang-ulang setiap kali halaman di load, sedangkan halaman yang dinamis yang umumnya berubah yaitu halaman content yang isinya berdasarkan hasil request. Berikut merupakan hirarki view (application/views) yang akan dibuat  :
  • template/ (direktori/folder)
    • header.php
    • content.php
    • footer.php
    • script.php
    • modal.php
    • index.php
  • login.php
  • user_area.php
  • user_detail.php
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>CodeIgniter Login Example Using Twitter Bootstrap</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="<?=base_url();?>css/bootstrap.min.css" rel="stylesheet">
    <link href="<?=base_url();?>css/bootstrap-responsive.min.css" rel="stylesheet">
    <link href="<?=base_url();?>css/style.css" rel="stylesheet">
  </head>
  <body>
Buat file content.php pada direktori application/views/template. Kosongkan isinya karena konten akan di generate dinamis dari controller.
<footer class="footer">
  <p>Copyright © 2013 - <a href="http://aditya-nursyahbani.com/">Aditya Nursyahbani</a></p>
</footer>
    </div><!-- /container -->
    <script src="<?=base_url();?>js/jquery-1.8.3.min.js"></script>
    <script src="<?=base_url();?>js/bootstrap.min.js"></script>
  </body>
</html>
<div id="help" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="helpLabel" aria-hidden="true">
  <div class="modal-header">  
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	<h3 id="helpLabel">Help</h3>
  </div><!-- /modal-header -->
  <div class="modal-body">
    <h4>Create Account</h4>
	<p>Create a new account for accessing the user area. You can fill the registration form and click submit button to proceed. After have an account, you can use your <code>Username</code> and <code>Password</code> for login.</p><hr/>
	<h4>Login</h4>
	<p>This is login menu for accessing user area. <code>Username</code> and <code>Password</code> are required.</p><hr/>
	<h4>Logout</h4>
	<p>This is logout menu for exit the application (user area) and destroy the active session.</p><hr/>
	<h4>View Account Detail</h4>
	<p>This menu display the current user account information.</p><hr/>
	<div class="media">
	  <a class="pull-left" href="#"><img class="media-object" src="<?=base_url('img/download.png');?>" width="64px" height="64px"></a>
	  <div class="media-body">
	    <h4 class="media-heading">Download the source code</h4>The source code for this application available on <a href="https://github.com/adit-gudhel/ci-login" target="_blank">GitHub</a> repository.
	  </div>
	</div>
    <div class="media">
      <a class="pull-left" href="#"><img class="media-object" src="<?=base_url('img/message.png');?>" width="64px" height="64px"></a>
      <div class="media-body">
        <h4 class="media-heading">Comments and questions</h4>Post your questions and comments on the my blog post link below.
      </div>
    </div>
    <div class="media">
      <a class="pull-left" href="#"><img class="media-object" src="<?=base_url('img/blog.png');?>" width="64px" height="64px"></a>
      <div class="media-body">
        <h4 class="media-heading">Tutorial</h4>See full tutorial on my blog post <a href="http://dityalovers.blogspot.com/2013/03/codeigniter-login-tutorial.html" target="_blank">CodeIgniter Login Tutorial</a>.
      </div>
    </div>
    <div class="media">
      <a class="pull-left" href="#"><img class="media-object" src="<?=base_url('img/twitter.png');?>" width="64px" height="64px"></a>
      <div class="media-body">
        <h4 class="media-heading">Follow me on Twitter</h4><a href="http://twitter.com/adit_gudhel" target="_blank">@adit_gudhel</a>.
      </div>
    </div><hr/>
  </div><!-- /modal-body -->
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  </div><!-- /modal-footer -->
</div><!-- /modal -->
<?= $this->load->view('template/header'); ?>
<?= $this->load->view($content); ?>
<?= $this->load->view('template/footer'); ?>
<?= $this->load->view('template/script'); ?>
<?php include 'template/modal.php'; ?>
<div class="navbar navbar-inverse navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">
      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
        <span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
      </a>
      <a class="brand" href="<?=base_url();?>">CodeIgniter</a>
      <div class="nav-collapse collapse">
        <ul class="nav pull-right">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button">Account <b class="caret"></b></a>
            <ul class="dropdown-menu dropdown-form">
              <li><?php
		        echo form_open('signin');
			    echo form_fieldset();
			    echo form_label('Username');
			    echo form_input('username');
			    echo form_fieldset_close();
			    echo form_fieldset();
			    echo form_label('Password');
			    echo form_password('password');
			    $data = array(      
			      'type'    => 'submit',
				  'class'   => 'btn pull-right',
				  'content' => 'Login'    
			    );
			    echo form_button($data);
			    echo form_fieldset_close();
			    echo form_close(); ?>
                <li class="divider"></li>
                <li><a href="#help" data-toggle="modal" data-target="#help">Help</a></li>
              </li>
            </ul>
          </li>
        </ul>
      </div><!--/.nav-collapse -->
    </div><!--/container -->
  </div><!--/.navbar-inner -->
</div><!--/.navbar -->
<div class="container"><?php
  if($this->session->flashdata('msg') != ''){
    echo '
    <div class="row-fluid">
      <div class="span12 alert alert-error">
        <button type="button" class="close" data-dismiss="alert">×</button>'.$this->session->flashdata('msg').'
      </div>
    </div>';
  }  
  if($this->session->flashdata('success') != ''){
    echo '
    <div class="row-fluid">
      <div class="span12 alert alert-success">
	    <button type="button" class="close" data-dismiss="alert">×</button>'.$this->session->flashdata('success').'
	  </div>
    </div>';
  } ?>
  <div class="row-fluid">
    <div class="span6">
	<?php
	  $data = array('class' => 'form-register');
	  echo form_open('signup',$data); ?>
      <h2 class="form-register-heading">Create Account</h2>
    <?php
	  $data = array('name' => 'fname', 'class' => 'input-block-level', 'placeholder' => 'First Name', 'value' => set_value('fname'));
	  echo form_input($data);
	  $data = array('name' => 'lname', 'class' => 'input-block-level', 'placeholder' => 'Last Name', 'value' => set_value('lname'));
	  echo form_input($data);
	  $data = array('name' => 'email', 'class' => 'input-block-level', 'placeholder' => 'Email Address', 'value' => set_value('email'));
	  echo form_input($data);
	  $data = array('name' => 'uname', 'class' => 'input-block-level', 'placeholder' => 'Username', 'value' => set_value('uname'));
	  echo form_input($data);
	  $data = array('name' => 'pass', 'class' => 'input-block-level', 'placeholder' => 'Password');
	  echo form_password($data);
	  $data = array('name' => 'repass', 'class' => 'input-block-level', 'placeholder' => 'Re-Password');
	  echo form_password($data);
	  $data = array('type' => 'submit', 'class' => 'btn btn-large btn-primary', 'content' => 'Submit');
	  echo form_button($data);
	  echo form_close();
	?>
    </div><!--/.span6 -->
    <div class="span6">
      <h1>Login Example</h1>
      <p>Welcome to CodeIgniter Login Example using session</p>
    <?php   
	  if(validation_errors()){
	    echo'
		<div class="row-fluid">
		  <div class="span12 alert alert-error">
		    <button type="button" class="close" data-dismiss="alert">×</button>'.validation_errors().'
	      </div>
		</div>';
	  }
	?>
    </div><!--/.span6 -->
  </div> <!--/row -->
<div class="navbar navbar-inverse navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">
	  <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
	  <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
	    <span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
	  </a>
	  <a class="brand" href="<?=base_url();?>user">CodeIgniter</a>
	  <div class="nav-collapse collapse">
	    <ul class="nav pull-right">
		  <li class="dropdown">
		    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button">
			<?= $this->session->userdata('username'); ?> <b class="caret"></b></a>
			<ul class="dropdown-menu dropdown-form">
			  <li><a href="<?=base_url();?>user/detail">View Account Detail</a></li>
			  <li class="divider"></li>
			  <li><a href="<?=base_url();?>signout">Logout</a></li>
			</ul>
		  </li><!--/.dropdown -->
	    </ul>
	  </div><!--/.nav-collapse -->
	</div><!--/.container -->
  </div><!--/.navbar-inner -->
</div><!--/.navbar -->
<div class="container">
  <div class="row">
    <div class="span12">
	  <div class="hero-unit">
	    <h1>Home</h1>
		<p>Welcome <strong><?=$this->session->userdata('username');?></strong>,<br/>This is the main user area.</p>
	  </div><!--/.hero-unit -->
	</div><!--/.span12 -->
  </div><!--/.row -->
<div class="navbar navbar-inverse navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">
      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
        <span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
      </a>
      <a class="brand" href="<?=base_url();?>user">CodeIgniter</a>
      <div class="nav-collapse collapse">
        <ul class="nav pull-right">
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"><?= $account['username']; ?> <b class="caret"></b></a>            <ul class="dropdown-menu dropdown-form">
              <li>
                <li><a href="<?=base_url();?>user/detail">View Account Detail</a></li>
                <li class="divider"></li>
                <li><a href="<?=base_url();?>signout">Logout</a></li>
              </li>
            </ul>
          </li>
        </ul>
      </div><!--/.nav-collapse -->
    </div>
  </div>
</div><!--/.navbar -->
<div class="container">
  <div class="row-fluid">
    <div class="span12">
      <div class="hero-unit">
        <h1><?= ucfirst($account['first_name']); ?> <?= ucfirst($account['last_name']); ?></h1>
        <p><?= $account['username']; ?></p>
      </div>
    </div>
  </div>
  <div class="row-fluid">
    <div class="span12">
      <legend>Your Account Detail :</legend>
      <div class="row-fluid">
        <div class="span8">
          <ul class="nav nav-tabs">
            <li class="active"><a href="#fname" data-toggle="tab">First Name</a></li>
            <li><a href="#lname" data-toggle="tab">Last Name</a></li>
            <li><a href="#email" data-toggle="tab">Email Address</a></li>
          </ul>
          <div class="tab-content">
            <div class="tab-pane active" id="fname"><p><?= $account['first_name']; ?></p></div>
            <div class="tab-pane" id="lname"><p><?= $account['last_name']; ?></p></div>
            <div class="tab-pane" id="email"><p><?= $account['email_address']; ?></p></div>
          </div>
        </div>
        <div class="span4"><p class="text-center"><img class="img-circle" width="140" height="140" src="<?= base_url('img/adit.jpg'); ?>"</p></div>
      </div>
    </div>
  </div>
Finally konfigurasi route.php (application/config) :
$route['user/logout'] = "login/logout";
$route['user/detail'] = "user/view_account";
$route['user'] = "user";

$route['signout'] = "login/logout";

$route['signin'] = "login/cek_login";
$route['signup'] = "login/signup";
$route[':any'] = "login";

$route['default_controller'] = "login";
$route['404_override'] = '';

Screenshoot aplikasi

CodeIgniter Login - Form Validation Error
CodeIgniter Login - Form Validation Error

CodeIgniter Login - Account Created
CodeIgniter Login - Account Created

CodeIgniter Login - Error when Username and Password empty
CodeIgniter Login - Error

CodeIgniter Login - Invalid Username and Password
CodeIgniter Login - Invalid Username and Password

CodeIgniter Login - View Account Detail
CodeIgniter Login - View Account Detail

Download the source code

0 comments:

Post a Comment