简体   繁体   中英

How to Check either Session is Set or Not in Codeigniter?

I know how to create session in core PHP, and I have understand how to do this in codeigniter, but I am unable to understand how to check, if the session is set or not? I have tried to check this through View but it always give me the meesage Please Login .

Kindly tell me how can I check whether the session is Set or not Set

Controller

if ($user_type=='Student')
{
  if ($LoginData=   $this->loginmodel->studentLogin($username,$password))
  {
    foreach($LoginData as $UserId)
    {
      $currentId= $UserId->StudentId;
    }
    //[[session]]

    $data['students_data']=         $this->loginmodel->student_profile($currentId);

    $this->session->userdata('$data');

    $this->load->view('students',$data);
  }
  else
  { 
  //$data['message']= array('Invalid Username or Password');
    $this->load->view('Login');
    echo "Invalid Username or Password";
  }
}
elseif ($user_type=="Faculty")
{
  if($data['faculty_data']=$this->loginmodel->faculty_admin($username, $password))
  {
    $this->session->userdata('$data');

    $this->load->view('faculty');
  }
  else
  {
    $this->load->view('Login');
    echo "Invalid Username or Password";
  }
}

VIEW

<?php 

if (!$this->session->userdata('$data'))
{
    echo "Please Login";
}
else
{

}

?>

<!DOCTYPE

Creating Session:

$newdata = array(
               'username'  => 'johndoe',
               'email'     => 'johndoe@some-site.com',
               'logged_in' => TRUE
           );

$this->session->set_userdata($newdata);

or

  $this->session->set_userdata('some_name', 'some_value');

But before that ensure that you have the session library included.

$this->load->library('session');

Get Session Data:

if($this->session->userdata('whatever_session_name_is')){
     // do something when exist
}else{
    // do something when doesn't exist
}
 if ($this->session->userdata('variable') !== FALSE) {
  echo 'Variable is set';
} else {
  echo 'Variable is not set';
}  

More info

Demo code

Using has_userdata

    if ($this->session->has_userdata('username')) {

        return TRUE;       

    } else {

        return FALSE;     

    }

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