Buat login di codeigniter dengan MVC

Membaut sistem login dengan codeigniter

Untuk membuat system logindengan codeigniter , kita harus membuat database dulu

Buat database dengan nama blog_tut setalah itu

Buat table dengan nama comments

CREATE TABLE `comments` (
  `id` smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
  `post_id` smallint(5) UNSIGNED NOT NULL,
  `name` varchar(60) collate latin1_general_ci NOT NULL,
  `email` varchar(100) collate latin1_general_ci NOT NULL,
  `body` text collate latin1_general_ci NOT NULL,
  `created_on` varchar(10) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `post_id` (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci COMMENT='Comments on Posts' AUTO_INCREMENT=1 ;

Buat juga table dengan nama posts

CREATE TABLE `posts` (
  `id` smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT,
  `title` varchar(255) collate latin1_general_ci NOT NULL,
  `slug` varchar(255) collate latin1_general_ci NOT NULL,
  `body` text collate latin1_general_ci NOT NULL,
  `created_on` varchar(10) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci COMMENT='Blog Posts' AUTO_INCREMENT=1 ;

Buat table dengan nama ‘users’

CREATE TABLE `users` (
  `id` smallint(2) UNSIGNED NOT NULL AUTO_INCREMENT,
  `username` varchar(20) collate latin1_general_ci NOT NULL,
  `password` varchar(100) collate latin1_general_ci NOT NULL,
  `email` varchar(100) collate latin1_general_ci NOT NULL,
  `display_name` varchar(40) collate latin1_general_ci NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci COMMENT='Registered Users Information' AUTO_INCREMENT=1

Setelah anda selesai membuat database, silahkan sekarang konfigurasi framework codeigniter anda dengan konfigurasi dibawa ini :

Configuration
ubah konfigurasi autoload.php:

$autoload['libraries'] = array('database', 'session');
$autoload['helper'] = array('url', 'form');

Buatlah konfigurasi config.php:

$config['base_url']    = "http://localhost/";
$config['log_threshold'] = 1;
$config['encryption_key'] = "blog_tut";
$config['sess_cookie_name']           = 'blog_tut_sess';
$config['sess_expiration']            = 0;
$config['sess_encrypt_cookie'] = TRUE;
$config['global_xss_filtering'] = TRUE;
$config['compress_output'] = TRUE;

Ubahlah konfigurasi database.php

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "blog_tut";

Yang terakhir ubah routes.php

$route['default_controller'] = "blog";

Mudah bukan untuk konfigurasi framework kodeigniter

The Controller
lalu setelah itu masuk kedalam menu controller dan beri nana denan nama : blog.php.

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

class Blog extends Controller {

        function Blog() {
               parent::Controller();
        }

        // Our front page
        function index() {
               $this->load->view('blog/front');
        }

        // We're viewing a single blog post
        function article() {
               $this->load->view('blog/article');
        }

        // We're writing a post
        function write() {
               $this->load->view('blog/write');
        }

}

?>

Setelah control diatas telah anda buat , anda harus membuat VIEW

Dibawah ini sample view dari write.view.php, yang nanti akan dipanggil di controller

View: blog/write

<?= form_open('blog/write'); ?>
        <p><label for="title">Title:</label><br />
        <input type="text" name="title" id="title" /></p>

        <p><label for="body">Body:</label><br />
        <textarea name="body" id="body" rows="40" cols="5"></textarea></p>

        <p><input type="submit" value="Post" /></p>

<?= form_close(); ?

User Registration
sebelum masuk kedalam post halaman web kita, maka kita perlu membuat halaman login terlebih dahulu

Buatlah control dengan nama

. Controller: user.php

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

class Blog extends Controller {

        function Blog() {
               parent::Controller();
        }

        // If logged in, send to front page
        // If not logged in, send to login form
        function index() {
        }

        // User Registration
        function register() {
               $this->load->view('user/register');
        }

        // User Login
        function login() {
               $this->load->view('user/login');
        }

}

?>

Setelah anda buat system controllnya anda perlu membua system view atau tampilan dari system login anda:

View: user/register

<?= form_open('user/register'); ?>

        <p><label for="username">Username:</label><br />
        <input type="text" name="username" id="username" /></p>

        <p><label for="email">Email:</label><br />
        <input type="text" name="email" id="email" /></p>

        <p><label for="display_name">Display Name:</label><br />
        <input type="text" name="display_name" id="display_name" /></p>

        <p><label for="password">Password:</label><br />
        <input type="password" name="password" id="password" /></p>

        <p><label for="password_conf">Retype Password:</label><br />
        <input type="password" name="password_conf" id="password_conf"></p>

        <p><input type="submit" value="Register" /></p>

<?= form_close(); ?>
 
 

Registration Validation

        // User Registration
        function register() {
               $this->load->library('validation');
               $rules['username'] = 'trim|required|min_length[3]|max_length[20]';
               $rules['email'] = 'trim|required|valid_email|max_length[100]';
               $rules['display_name'] = 'trim|required|min_length[3]|max_length[40]';
               $rules['password'] = 'trim|required|min_length[3]|max_length[20]';
               $rules['password_conf'] = 'trim|matches[password]';
               $this->validation->set_rules($rules);
               $fields['username'] = 'username';
               $fields['email'] = 'email address';
               $fields['display_name'] = 'display name';
               $fields['password'] = 'password';
               $fields['password_conf'] = 'password confirmation';
               $this->validation->set_fields($fields);
               if ($this->validation->run()) {
                       $this->load->library('security');
                       $insert = array(
                               'username' => $this->input->post('username'),
                               'email' => $this->input->post('email'),
                               'display_name' => $this->input->post('display_name'),
                               'password' => dohash($this->input->post('password'))
                               );
                       $this->db->insert('users', $insert);
                       redirect('blog');
                } else {
                       $this->load->view('user/register');
               }
        }

1035

Username/Email Check
We want to make sure we’re not registering the same username/password twice, so let’s create a callback function for that.

        // Check username/email for uniqueness
        function _check_username($username) {
               $email = $this->validation->email;
               $query = $this->db->getwhere('users', array('username'=>$username), 1, 0);
               if ($query->num_rows() != 0) {
                       $this->validation->set_message('_check_username', 'This username has already been registered');
                       return FALSE;
               } else {
                       $query = $this->db->getwhere('users', array('email'=>$email), 1, 0);
                       if ($query->num_rows() != 0) {
                               $this->validation->set_message('_check_username', 'This email address has already been registered');
                               return FALSE;
                       }
               }
               return TRUE;
        }

Kemudian perbarui rules a bit:

$rules['username'] = 'trim|required|min_length[3]|max_length[20]|callback__check_username';

Untuk selanjutnya silahkan otak atik sendiri dan coba-mencaba dan terus belajar he he , salam codeigniter

Register
Now let’s go see if we can register – if everything works correctly we should be presented an error saying it can’t find our view file for the index() method in the blog class.

Found my first syntax error – update the User Controller with the following (darn, copy-paste):

class User extends Controller {

Another error, security is a helper, not a library. Update the same file:

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

Alright, just checked the database – my user was created, now let’s work on logging in. We’ll start this by creating our blog/front view.

View: blog/front

<?php
        if ($user['logged_in'] === TRUE) {
               echo anchor('user/logout', 'Logout');
        } else {
               echo anchor('user/login', 'Login');
        }
?>

Blog Controller

        function index() {
               if ($this->session->userdata('logged_in')) {
                       $data['user']['logged_in'] = TRUE;
               } else {
                       $data['user']['logged_in'] = FALSE;
               }
               $this->load->view('blog/front', $data);
        }

Logging In – View: user/login.php
Visit your blog controller and you should be presented with a Login link – we now need to create the view for that.

<?= form_open('user/login'); ?>

        <p><label for="username">Username:</label><br />
        <input type="text" name="username" id="username" /></p>

        <p><label for="password">Password:</label><br />
        <input type="password" name="password" id="password" /></p>

        <p><input type="submit" value="Login" /></p>

<?= form_close(); ?>

1052

Login Validation
A lot of changes here… in the user controller

// User Login
        function login() {
               $this->load->library('validation');
               $rules['username'] = 'trim|required|callback__check_login';
               $rules['password'] = 'trim|required';
               $this->validation->set_rules($rules);
               $fields['username'] = 'username';
               $fields['password'] = 'password';
               $this->validation->set_fields($fields);
               if ($this->validation->run()) {
                       $query = $this->db->getwhere('users', array('username' => $this->input->post('username')));
                       $row = $query->row();
                       $this->session->set_userdata('logged_in', $row->id);
                       redirect('blog');
               } else {
                       $this->load->view('user/login');
               }
        }

        // Check the login information
        function _check_login($username) {
               $this->load->helper('security');
               $password = dohash($this->validation->password);
               $query = $this->db->getwhere('users', array('username'=>$username, 'password'=>$password), 1, 0);
               if ($query->num_rows() == 0) {
                       $this->validation->set_message('_check_login', 'Invalid login');
                       return FALSE;
               }
               return TRUE;
        }

Time to test and see if that works.

1059

Worked like a charm. Now that we’re logged in (and we have our user id stored in the session) – we can go back to authoring a post. Let’s write a check and make sure people can’t get to this page unless they are logged in.

Controller blog

        // We're writing a post
        function write() {
               if ($this->session->userdata('logged_in') === FALSE) {
                       redirect('blog');
               }
               $this->load->view('blog/write');
        }

Whoah! Visited by writing page and my textarea is all jacked up – I always get the rows/columns backwards.

<p><label for="body">Body:</label><br />
        <textarea name="body" id="body" rows="50" cols="40"></textarea></p>

Still excessive, drop the rows to 20.

Making a Post
Now we’re going to write the functionality to actually make a blog post.

I just realized I didn’t add in a field to the posts table to account for the author, perform the following query on that table:

ALTER TABLE `posts` ADD `author_id` SMALLINT UNSIGNED NOT NULL AFTER `slug` ;

ALTER TABLE `posts` ADD INDEX ( `author_id` ) ;

Make these changes to the blog controller:

        // We're writing a post
        function write() {
               if ($this->session->userdata('logged_in') === FALSE) {
                       redirect('blog');
               }
               $this->load->library('validation');
               $rules['title'] = 'trim|required|min_length[3]|max_length[255]';
               $rules['body'] = 'trim|required';
               $this->validation->set_rules($rules);
               $fields['title'] = 'title';
               $fields['body'] = 'body';
               $this->validation->set_fields($fields);
               if ($this->validation->run()) {
                       $this->load->helper('date');
                       $insert = array(
                               'title' => $this->input->post('title'),
                               'slug' => url_title($this->input->post('title')),
                               'author_id' => $this->session->userdata('logged_in'),
                               'body' => $this->input->post('body'),
                               'created_on' => now()
                       );
                       $this->db->insert('posts', $insert);
                       redirect('blog');
               } else {
                       $this->load->view('blog/write');
               }
        }

Now test to see if we make a post.

Sure enough it worked – let’s list all of our posts on the front page now – as well as a link to write a post.

List Posts
In blog.php Controller:

        // Our front page
        function index() {
               if ($this->session->userdata('logged_in')) {
                       $data['user']['logged_in'] = TRUE;
               } else {
                       $data['user']['logged_in'] = FALSE;
               }
               $query = $this->db->get('posts');
               foreach ($query->result() as $row) {
                       $data['posts'][$row->id]['title'] = $row->title;
               }
               $this->load->view('blog/front', $data);
        }

In blog/front View:

<?php
        if ($user['logged_in'] === TRUE) {
               echo anchor('user/logout', 'Logout');
               echo '<br /';
               echo anchor('blog/write', 'Write a Post');
        } else {
               echo anchor('user/login', 'Login');
        }
?>
<p></p>
<?      
        foreach ($posts as $id => $post) {
               echo 'Post #' . $id . ': ';
               echo anchor('blog/article/' . $id, $post['title']);
               echo '<br />';
        }
?>
 
 
 
 

 Salam codeigniter

Comments
8 Responses to “Buat login di codeigniter dengan MVC”
  1. kartieka mengatakan:

    sy dh coba utk run tp ngapa in register nye ngak msk dlm dbase ya??

  2. harry mengatakan:

    itu dari tulisannya michael wales ya? saya pernah nyoba tapi malah pusing sendiri, akhirnya bikin sendiri deh😀

  3. krida mengatakan:

    mas iorme iya itu hasil ngopi paste” yang versi indonesianya tolong di posting dong

  4. pemula mengatakan:

    makasih tutorialnya.. kalo sempat dibuat lebih mudah buat para pemula…

  5. krida mengatakan:

    insyaalah nanti akan aku buat model login yang mudah dengan codeigniter

  6. Loy99 mengatakan:

    Are threshold values of the required amount -high multiples of the average heat energy kT – reasonable, are they within the range known from ordinary chemistry? ,

  7. arifsyahputra mengatakan:

    gue pengen cari temen sebnyak bnyak nya, bagi yg berminat email gue aja.

  8. andi_bazo mengatakan:

    gimana ya caranx daftarrr

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: