echo user in view from sessions code igniter

user1972143 picture user1972143 · Jan 15, 2013 · Viewed 27.3k times · Source

I am new in codeigniter. I have implemented a simple login system. I want to print out a username on my view page which is stored in sessions. here is my controller

class LoginController extends CI_Controller {

function index(){           
        $new['main_content'] = 'loginView';
        $this->load->view('loginTemplate/template', $new); 

    }   

    function verifyUser(){          
        //getting parameters from view 
        $data = array(
                'username' => $this->input->post('username'),
                'password' => $this->input->post('password')
        );          

        $this->load->model('loginModel'); 
        $query = $this->loginModel->validate($data);   

              if ($query){             
            //if the user c validated
            //data variable is created becx we want to put username in session
                $data = array(
                    'username' => $this->input->post('username'),
                     'is_logged_in' => true 
                );

               $this->session->set_userdata($data);
             redirect('sessionController/dashboard_area');
        }
        else
         {
            $this->index();
        }
    }
    function logout()
    {
        $this->session->sess_destroy();
        $this->index();
    }
    }
    ?>

sessionController

<?php

          class SessionController extends CI_Controller {

function __construct()
{
    parent::__construct();
    $this->is_logged_in();

}



function dashboard_area(){


    $data['main_content'] = 'dashboardView';
    $this->load->view('dashboardTemplate/template', $data);

}

function is_logged_in()
{
    $is_logged_in = $this->session->userdata('is_logged_in');
    if(!isset($is_logged_in) || $is_logged_in != true)
    {
        echo 'You don\'t have permission to access this page.';
        die();
        //$this->load->view('login_form');
    }else {

    return true;

    }
}


       }
  ?>

how can i stored a username in sessions and then print out in a page ... i dont want to save username in every controller

if any one have a better suggestions to implement then please share it to me ..

Answer

cartina picture cartina · Jan 15, 2013
$username = $this->session->userdata('username');

//Pass it in an array to your view like
$data['username']=$username;   
$this->load->view('test',$data);

//Then in you view you can display it as:
 echo $username;