Membuat Login Multiuser dengan Template AdminLTE + Codeigniter



Membuat login Multiuser dengan framework codeigniter yang di integrasikan menggunakan template AdminLTE , dalam kesempatan kali ini saya akan membagikan bagaimana membuat session multiuser dengan Codeigniter langsung ke tkp;

1. Buat tabel user kedalam database anda ( disini saya menggunakan Mysql )
INSERT INTO `user` (`u_id`, `nama`, `u_name`, `u_paswd`, `role`) VALUES (1, 'andrian', 'andrianext', '21232f297a57a5a743894a0e4a801fc3', 'admin'),(2, 'user admin', 'user', '21232f297a57a5a743894a0e4a801fc3', 'user');
2. Download source Codeigniter versi 2.2 Stable di : www.codeigniter.com/download
3. Extrak dan copy file CI yang sudah di download tersebut ke webserver local anda
4. Kalo menggunakan xampp tarus file tersebut di htdocs, rename nama project sesuai selera anda
5. Setelah itu akan terlihat direktori folder tersebut seperti ini :


6. Buka folder application- controllers, disitu buat contraller dengan nama login.php dan masukan script di bawah ini;

<?php
class Login extends CI_Controller {
    function __construct() {
        parent::__construct();
        session_start();
        $this->load->model(array('m_user'));
        if ($this->session->userdata('u_name')) {
            redirect('dashboard');
        }
    }
    function index() {
        $this->load->view('login');
    }
    function proses() {
        $this->form_validation->set_rules('username', 'username', 'required|trim|xss_clean');
        $this->form_validation->set_rules('password', 'password', 'required|trim|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('login');
        } else {
            $usr = $this->input->post('username');
            $psw = $this->input->post('password');
            $u = mysql_real_escape_string($usr);
            $p = md5(mysql_real_escape_string($psw));
            $cek = $this->m_user->cek($u, $p);
            if ($cek->num_rows() > 0) {
                //login berhasil, buat session
                foreach ($cek->result() as $qad) {
                    $sess_data['u_id'] = $qad->u_id;
                    $sess_data['nama'] = $qad->nama;
                    $sess_data['u_name'] = $qad->u_name;
                    $sess_data['role'] = $qad->role;
                    $this->session->set_userdata($sess_data);
                }
                redirect('dashboard');
            } else {
                $this->session->set_flashdata('result_login', '<br>Username atau Password yang anda masukkan salah.');
                redirect('login');
            }
        }
    }
    function logout() {
        $this->session->sess_destroy();
        redirect('login');
    }
}

7. Buat model di application- models , berinama m_user.php dan copykan script dibawah ini
<?php
class M_user extends CI_Model {
    private $table = "user";
    function cek($username, $password) {
        $this->db->where("u_name", $username);
        $this->db->where("u_paswd", $password);
        return $this->db->get("user");
    }
    function semua() {
        return $this->db->get("user");
    }
    function cekKode($kode) {
        $this->db->where("u_name", $kode);
        return $this->db->get("user");
    }
    function cekId($kode) {
        $this->db->where("u_id", $kode);
        return $this->db->get("user");
    }
    function getLoginData($usr, $psw) {
        $u = mysql_real_escape_string($usr);
        $p = md5(mysql_real_escape_string($psw));
        $q_cek_login = $this->db->get_where('users', array('username' => $u, 'password' => $p));
        if (count($q_cek_login->result()) > 0) {
            foreach ($q_cek_login->result() as $qck) {
                foreach ($q_cek_login->result() as $qad) {
                    $sess_data['logged_in'] = 'aingLoginWebYeuh';
                    $sess_data['u_id'] = $qad->u_id;
                    $sess_data['u_name'] = $qad->u_name;
                    $sess_data['nama'] = $qad->nama;
                    $sess_data['group'] = $qad->group;
                    $sess_data['rid'] = $qad->rid;
                    $this->session->set_userdata($sess_data);
                }
                redirect('dashboard');
            }
        } else {
            $this->session->set_flashdata('result_login', '<br>Username atau Password yang anda masukkan salah.');
            header('location:' . base_url() . 'login');
        }
    }
}


8. Setelah kita buat controller dan model untuk menu login kemudian kita buat view nya di application - views, dengan nama login.php dan copykan script seperti dibawah ini; 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Andrianext | Log in</title>
        <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
        <!-- Bootstrap 3.3.2 -->
        <link href="<?php echo base_url('assets/css/bootstrap.min.css'); ?>" rel="stylesheet" >
        <!-- Font Awesome Icons -->
        <link href="<?php echo base_url('assets/css/font-awesome.min.css'); ?>" rel="stylesheet">
        <!-- Theme style -->
        <link href="<?php echo base_url('assets/css/AdminLTE.min.css'); ?>" rel="stylesheet">    
        <!-- iCheck -->
        <link href="<?php echo base_url('assets/js/plugins/iCheck/square/blue.css'); ?>" rel="stylesheet">
    </head>
    <body class="login-page">
        <div class="login-box">
            <div class="login-logo">
                <a href="#" ><b>Andria</b>Next</a>
            </div><!-- /.login-logo -->
            <div class="login-box-body">
                <p class="login-box-msg">Sign in to start your session </p>
                <form action="<?php echo site_url('login/proses'); ?>" method="post">
                    <?php
                    if (validation_errors() || $this->session->flashdata('result_login')) {
                        ?>
                        <div class="alert alert-error">
                            <button type="button" class="close" data-dismiss="alert">&times;</button>
                            <strong>Warning!</strong>
                            <?php echo validation_errors(); ?>
                            <?php echo $this->session->flashdata('result_login'); ?>
                        </div>
                    <?php } ?>
                    <div class="form-group has-feedback">
                        <input type="text" name="username" class="form-control" placeholder="Username"/>
                        <span class="glyphicon glyphicon-user form-control-feedback"></span>
                    </div>
                    <div class="form-group has-feedback">
                        <input type="password" name="password" class="form-control" placeholder="Password"/>
                        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
                    </div>
                    <div class="row">
                        <div class="col-xs-8">
                            <div class="checkbox icheck">
                                <label>
                                    <input type="checkbox"> Remember Me
                                </label>
                            </div>                    
                        </div><!-- /.col -->
                        <div class="col-xs-4">
                            <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
                        </div><!-- /.col -->
                    </div>
                </form>            
                <div class="social-auth-links text-center">
                    <p>- OR -</p>
                    <a href="#" class="btn btn-block btn-social btn-facebook btn-flat"><i class="fa fa-facebook"></i> Sign in using Facebook</a>
                    <a href="#" class="btn btn-block btn-social btn-google-plus btn-flat"><i class="fa fa-google-plus"></i> Sign in using Google+</a>
                </div><!-- /.social-auth-links -->
                <a href="#">I forgot my password</a><br>
                <a href="register.html" class="text-center">Register a new membership</a>
            </div><!-- /.login-box-body -->
        </div><!-- /.login-box -->
        <!-- jQuery 2.1.3 -->
        <script src="<?php echo base_url('assets/js/plugins/jQuery/jQuery-2.1.3.min.js'); ?>"></script>
        <!-- Bootstrap 3.3.2 JS -->
        <script src="<?php echo base_url('assets/js/bootstrap.min.js'); ?>"></script>
        <!-- iCheck -->
        <script src="<?php echo base_url('assets/js/plugins/iCheck/icheck.min.js'); ?>"></script>  
        <script>
            $(function () {
                $('input').iCheck({
                    checkboxClass: 'icheckbox_square-blue',
                    radioClass: 'iradio_square-blue',
                    increaseArea: '20%' // optional
                });
            });
        </script>
    </body>
</html>
9. Copykan folder assets yang berisi ccs dan javascript yang sudah di custume dari template bootstrap AdminLTE2.0, dan bisa di download di bawah ini.
10. Coba buka project anda misal ; http://localhost/andrianext/ ,


11. Masukan User: andrianext  , Password : admin sebagai login administrator/admin
12. Maka Hasilnya akan seperti gambar di bawah ini;

13. Dan kita coba login dengan user : user , Password : admin , lihat di gambar yang di lingkari merah,akan nampak perbedaan di jenis user login ya, Administrator / User.



14. Demikian tutorial untuk membuat menu login multi user, untuk source codenya anda bisa download di mari. http://adf.ly/1AFsNu


28 comments

ijin sedot gan, tp pas saya buka di localhost/blablabla kok g bisa ya. kira2 apanya yg salah? mohon bantuannya, terimakasih

Luar biasa.. Scriptnya cemerlang.
Butuh seharian juga ternyata belajar memahami script2 tsb. Newbie banget.. ;)

Muncul pertanyaan besar nih:
Bagaimana jika role loginnya ada 10 jenis.
Terus msg2 jenis role punya batasan tampilan menu2 pada dashboardnya.
Role_1 hanya muncul menu 1, 2, 5, 9
Role_2 hanya muncul menu 2, 5, 7, 8
Role_3 hanya muncul menu 1, 2, 4, 9
Dst....
Role_10 muncul semua menu

Mohon pencerahannya Om.

mantep gan, ane utak atik dikit
idem ama yang diatas pertanyaannya

bisa saja di menu dashboard dibuat if ,else
jadi nanti ketika login session role = role_1 maka akan ditampilkan menu 1,2,5,9 jika session role= role_2 maka akan tampil menu 2,5,7,8,dan jika session role=role_3 akan tampil menu 1,2,4,9 dst.

keren... joss..mantap..suer :D

pertanyaannya sama ka mas Razali Adam,itu nanti script if, elsenya disimpen dimana ya, apa langsung di viewnya atau bikin dlu di controller (maaf masih nubie hehehe)

gan tanya, muncul error gini, napa yak?


A PHP Error was encountered

Severity: Notice

Message: Undefined property: Login::$session

Filename: controllers/login.php

Line Number: 7

Backtrace:

File: E:\xampp\htdocs\project_telkom\application\controllers\login.php
Line: 7
Function: _error_handler

File: E:\xampp\htdocs\project_telkom\index.php
Line: 292
Function: require_once


Fatal error: Call to a member function userdata() on null in E:\xampp\htdocs\project_telkom\application\controllers\login.php on line 7
A PHP Error was encountered

Severity: Error

Message: Call to a member function userdata() on null

Filename: controllers/login.php

Line Number: 7

Backtrace:

untuk autoload library session ya udah di tambahkan belum?

coba cek di application/config/autoload.php
$autoload['libraries'] = array('database','session','form_validation','template');

Halo mas, kenapa saya punya keluar beginian ya ?

A Database Error Occurred

Unable to connect to your database server using the provided settings.

Filename: E:\UniServer\www\gsp\userarea\system\database\DB_driver.php

Line Number: 125

coba cek di koneksi databasenya; config | database.php

mungkin seting username ama password localhost anda belum sesuai.

udah ditambahan sessionnya di autoload kok masih eror kya gini ya master

A PHP Error was encountered

Severity: Notice

Message: A session had already been started - ignoring session_start()

Filename: controllers/login.php

Line Number: 6

Backtrace:

File: C:\xampp\htdocs\warung\application\controllers\login.php
Line: 6
Function: session_start

File: C:\xampp\htdocs\warung\index.php
Line: 292
Function: require_once

Hapus session_start(); yang ada di controllers/login.php,

kemungkinan session nya double

thanks gan tutorialnya, ini yang saya cari-cari.

gan, ane setiap login selalu warning username dan password salah, padahal sudah benar dan dicoba berulang kali..
kira2 masalahnya dimana ya ?

untuk user default: andrianext , password: admin


Fatal error: Uncaught Error: Call to undefined function mysql_pconnect() in C:\xampp\htdocs\andrianext\system\database\drivers\mysql\mysql_driver.php:92 Stack trace: #0 C:\xampp\htdocs\andrianext\system\database\DB_driver.php(116): CI_DB_mysql_driver->db_pconnect() #1 C:\xampp\htdocs\andrianext\system\database\DB.php(149): CI_DB_driver->initialize() #2 C:\xampp\htdocs\andrianext\system\core\Loader.php(347): DB(Array, NULL) #3 C:\xampp\htdocs\andrianext\system\core\Loader.php(1172): CI_Loader->database() #4 C:\xampp\htdocs\andrianext\system\core\Loader.php(153): CI_Loader->_ci_autoloader() #5 C:\xampp\htdocs\andrianext\system\core\Controller.php(52): CI_Loader->initialize() #6 C:\xampp\htdocs\andrianext\application\controllers\login.php(5): CI_Controller->__construct() #7 C:\xampp\htdocs\andrianext\system\core\CodeIgniter.php(309): Login->__construct() #8 C:\xampp\htdocs\andrianext\index.php(202): require_once('C:\\xampp\\htdocs...') #9 {main} thrown in C:\xampp\htdocs\andrianext\system\database\drivers\mysql\mysql_driver.php on line 92

seting di config |database.php udah di sesuaikan belum mas

Warning!

Unable to access an error message corresponding to your field name username.(xss_clean)

Unable to access an error message corresponding to your field name password.(xss_clean)


Kalo itu kenapa ya mas ..??

coba buka aplication->view->login.php
cari code
<form action="<?php echo site_url('login/proses'); ?>" method="post">
dan ubah menjadi <?php echo form_open('login/proses'); ?>

tetep mas..kagak bisa .. kagak ada perubahan

salah di login/proses nya mas dari tadi di coba kagak ada perubahan mas...

coba buka controllers nya trus form_validation->set_rules(xss_clean) ya dihilangkan


EmoticonEmoticon