简体   繁体   中英

How to get username with sessions in codeigniter

I'm making a very simple login autenthication with Codeigniter(3) with two simple fields , username and password. I'm very new with this and I'm having some problems. This is my controller to verify if the User has entered correct credentials:

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

class VerifyLogin extends CI_Controller {

 function __construct()
 {
   parent::__construct();
   $this->load->model('user','',TRUE);
   $this->load->helper('url');

 }

 function index()
 {
   //This method will have the credentials validation
   $this->load->library('form_validation');

   $this->form_validation->set_rules('username', 'Username', 'trim|required');
   $this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');

   if($this->form_validation->run() == FALSE)
   {
     //Field validation failed.  User redirected to login page
     $this->load->view('login_view');
   }
   else
   {
// session data

      $session_data = $this->session->userdata('logged_in');
     $data['username'] = $session_data['username'];
     $this->load->view('admin/dashboard', $data);

   }

     redirect(site_url('admin/dashboard'), 'refresh');


 }

 function check_database($password)
 {
   //Field validation succeeded.  Validate against database
   $username = $this->input->post('username');

   //query the database
    $result = $this->user->login($username, $password);

   if($result)
   {

     $sess_array = array();
     foreach($result as $row)
     {
       $sess_array = array(
         'id' => $row->id,
         'username' => $row->username
       );

       $this->session->set_userdata('logged_in', $sess_array);
     }
     return TRUE;
   }
   else
   {
     $this->form_validation->set_message('check_database', 'Invalid username or password');
     return false;
   }
 }
}
?> 

While the model user.php is this one:

function login($username, $password)
 {

$this -> db -> select('id, username, password');
$this -> db -> from('users');
$this -> db -> where('username', $username);
$this -> db -> where('password', $password);
$this -> db -> limit(1);

   $query = $this -> db -> get();

   if($query -> num_rows() == 1)
   {
     return $query->result();
   }
   else
   {
     return false;
   }
 }

When in my View I type Welcome <?php echo $username; ?> <?php echo $username; ?> I got undefined variable username. What I'm wrong?

Your session is working fine as per your comments, you just need to remove redirection, don't know why are you using?

Remove this line:

redirect(site_url('admin/dashboard'), 'refresh');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM