CodeIgniter Back to Latest Page After Logout

Now I will try to explain example back to latest page after logout from CodeIgniter Apps.
Oke and now this is example source code:

  1. Create Database admin for verify login page (Example I using PostgreSQL):
    CREATE TABLE admin
    (
      username character varying(50) NOT NULL,
      password character varying(150) NOT NULL,
      nama character varying(50),
      email character varying(100)
    )
    
  2. And then, we must create models to connect database and to check form input from form login page. application/models/m_login.php:
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
     
    class M_login extends CI_Model {
    
        function __construct() {
            parent::__construct();
            $this->load->database();
        }
    
        function login($username, $password) {
            //create query to connect user login database
            $this->db->select('username, password');
            $this->db->from('admin');
            $this->db->where('username', $username);
            $this->db->where('password', MD5($password));
            $this->db->limit(1);
            
            //get query and processing
            $query = $this->db->get();
            if($query->num_rows() == 1) { 
                return $query->result(); //if data is true
            } else {
                return false; //if data is wrong
            }
        }
    }
     
    /* End of file m_login.php */
    /* Location: ./application/models/m_login.php */
    

  3. Create Controller with name c_login to load view login page
    application/controllers/c_login.php:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class C_login extends CI_Controller {
    	public function __construct() {
    		parent::__construct();
            $this->load->model('m_login','login',TRUE);
         	$this->load->helper(array('form','html','url','html'));
         	$this->load->library(array('form_validation','session'));
    	}
    
        public function index() {
            $this->load->view('v_login'); //load view for login
        }
    
        public function login() {
           $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
    
            if($this->form_validation->run() == FALSE) {
                //Field validation failed.  User redirected to login page
                $this->load->view('v_login');
                } else {
                    redirect(site_url('c_home'), 'refresh');
                }       
         }
    
        public function check_database($password) {
             //Field validation succeeded.  Validate against database
             $username = $this->input->post('username');
             //query the database
             $result = $this->login->login($username, $password);
             if($result) {
                 $sess_array = array();
                 foreach($result as $row) {
                     //create the session
                     $sess_array = array('nama_admin' => $row->username);
                     //set session with value from database
                     $this->session->set_userdata('logged_in', $sess_array);
                     }
              return TRUE;
              } else {
                  //if form validate false
                  $this->form_validation->set_message('check_database', 'Invalid username or password');
                  return FALSE;
              }
          }
    }
    /* End of file c_login.php */
    /* Location: ./application/controllers/c_login.php */
    
  4. And this view for c_login. application/views/v_login.php
    <!DOCTYPE html>
    <html>
     <head>
       <title>Simple Login with CodeIgniter</title>
     </head>
     <body>
       <h1>Simple Login with CodeIgniter</h1>
       <?php echo validation_errors(); ?>
       <?php echo form_open('c_login/login');
       echo form_label("Username: ");
       echo form_input("username");
       echo br();
       echo form_label("Password: ");
       echo form_password("password");
       echo br();
       echo form_submit("","Login");
       echo form_close();
       ?>
     </body>
    </html>
    
  5. After create c_login, we must create controller again with name c_home. c_home controller is used as a redirect page if the username and password you have entered it correctly. See line 23 on the c_login controller.
    application/controllers/c_home.php:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class C_home extends CI_Controller {
        function __construct() {
            parent::__construct();
            $this->load->helper('url');
            $this->load->library(array('form_validation','session'));
        }
    
        function index() {
            if($this->session->userdata('logged_in'))
            {
                $session_data = $this->session->userdata('logged_in');
                $data['username'] = $session_data['nama_admin'];
                $this->load->view('v_home', $data);
            } else {
            //If no session, redirect to login page
                redirect('c_login', 'refresh');
            }
        }
    
        function logout() {
             //remove all session data
             $this->session->unset_userdata('logged_in');
             $this->session->sess_destroy();
             redirect(site_url("c_login?continue=".$this->input->get('continue')), 'refresh');
         }
    
    }
    /* End of file c_home.php */
    /* Location: ./application/controllers/c_home.php */
    
  6. And the last, we create page view home. application/views/v_home.php:
    <!DOCTYPE html>
     <head>
       <title>Simple Login with CodeIgniter - Private Area</title>
     </head>
     <body>
       <h1>Home</h1>
       <h2>Welcome <?php echo $username; ?>!</h2>
       <a href="<?php echo site_url('c_home/logout') ?>">Logout</a>
     </body>
    </html>
    

Okay we have finished creating a login form with an example application using the session. And what about the title above mean?
Oke to create that, first we must change:

  1. Change v_home.php to be like this:
    <!DOCTYPE html>
     <head>
       <title>Simple Login with CodeIgniter - Private Area</title>
     </head>
     <body>
       <h1>Home</h1>
       <h2>Welcome <?php echo $username; ?>!</h2>
       <a href="<?php echo site_url('c_user'); ?>">User Page</a>
       <a href="<?php echo site_url('c_home/logout?continue=').current_url(); ?>">Logout</a>
     </body>
    </html>
    

    Note:
    <?php echo site_url(‘c_user’); ?> is another example page. We create later.
    <?php echo site_url(‘c_home/logout?continue=’).current_url(); ?>. This is a function to get url if we want back to lates page after logout. site_url(‘c_home/logout?continue=’), we get result http://localhost/CodeIgniter/index.php/c_login?continue=. And current_url();, we will get the url address of the page that are our current access. So example we get url http://localhost/CodeIgniter/index.php/c_login?continue=http://localhost/CodeIgniter/index.php/c_user after we click logout link on page v_login.
    current_url()

  2. And then, now change v_login.php to be like this:
    <!DOCTYPE html>
    <html>
     <head>
       <title>Simple Login with CodeIgniter</title>
     </head>
     <body>
       <h1>Simple Login with CodeIgniter</h1>
       <?php echo validation_errors(); ?>
       <?php echo form_open('c_login/login');
       echo form_label("Username: ");
       echo form_input("username");
       echo br();
       echo form_label("Password: ");
       echo form_password("password");
       echo form_hidden('continue', $this->input->get('continue'));
       echo br();
       echo form_submit("","Login");
       echo form_close();
       ?>
     </body>
    </html>
    

    Note:
    echo form_hidden(‘continue’, $this->input->get(‘continue’)); in this chapter, I using form helper from CodeIgniter. Or same with <input type=”hidden” name=”continue” value=”<php echo $_GET[‘continue’]; ?>” />. Why I use form input? This input used to send url for continue page after logout. For more detail, see next chapter.

  3. Change c_login.php to be like this:

    public function login() {
           $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
    
            if($this->form_validation->run() == FALSE) {
                //Field validation failed.  User redirected to login page
                $this->load->view('v_login');
                } else {
                    $url = $this->input->post('continue') ? $this->input->post('continue') : site_url('c_home');
                    redirect($url, 'refresh');
                }       
         }
    
  4. And then, change c_home to be like this:
    function logout() {
             //remove all session data
             $this->session->unset_userdata('logged_in');
             $this->session->sess_destroy();
             redirect(site_url("c_login?continue=".$this->input->get('continue')), 'refresh');
         }
    
  5. And the last, create c_user and v_user. application/controllers/c_user.php:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class C_user extends CI_Controller {
        function __construct() {
            parent::__construct();
            $this->load->helper('url');
            $this->load->library(array('form_validation','session'));
        }
    
        function index() {
            if($this->session->userdata('logged_in'))
            {
                $session_data = $this->session->userdata('logged_in');
                $data['username'] = $session_data['nama_admin'];
                $this->load->view('v_user', $data);
            } else {
            //If no session, redirect to login page
                redirect('c_login', 'refresh');
            }
        }
    }
    /* End of file c_home.php */
    /* Location: ./application/controllers/c_home.php */
    
  6. application/views/v_user.php:
    <!DOCTYPE html>
     <head>
       <title>Simple Login with CodeIgniter - Private Area</title>
     </head>
     <body>
       <h1>Home</h1>
       <h2>Welcome User!</h2>
       <a href="<?php echo site_url('c_home'); ?>">Home Page</a>
       <a href="<?php echo site_url('c_home/logout?continue=').current_url(); ?>">Logout</a>
     </body>
    </html>
    

And finish…. ūüėÄ

Advertisements

19 comments

  1. I don’t know whether it’s just me or if everyone else experiencing problems with your blog.
    It looks like some of the written text in your content are running off the screen. Can somebody else please comment and let me know if this is happening to them too?
    This may be a issue with my web browser because I’ve had this happen previously.
    Thank you

  2. I loved as much as you’ll receive carried out right here. The sketch is tasteful, your authored material stylish.
    nonetheless, you command get got an impatience over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly the same nearly very often inside case you shield this increase.

  3. I’m amazed, I must say. Rarely do I encounter
    a blog that’s equally educative and engaging, and let
    me tell you, you’ve hit the nail on the head.

    The problem is an issue that not enough people are speaking intelligently about.
    I am very happy that I stumbled across this in my search for something regarding this.

  4. Can I simply just say what a relief to discover someone that truly knows what they are discussing on the internet.

    You certainly realize how to bring an issue to light and make it
    important. A lot more people should look at this and understand this side of your story.
    I was surprised you aren’t more popular given that you
    most certainly possess the gift.

  5. It’s a pity you don’t have a donate button! I’d without
    a doubt donate to this fantastic blog! I suppose for now i’ll settle for
    bookmarking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will talk about this site with my Facebook group.

    Talk soon!

  6. Thanks for the marvelous posting! I truly enjoyed reading it, you could be a great author.I will remember to bookmark your blog and will often come back later on. I want to encourage that you continue your great work, have a nice day!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s