php 如何在 Codeigniter 中检查会话是否设置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22985671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:24:31  来源:igfitidea点击:

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

phphtmlmysqlcodeignitersession

提问by user3480644

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.

我知道如何在核心 PHP 中创建会话,并且我已经了解如何在 codeigniter 中执行此操作,但是我无法理解如何检查会话是否已设置?我试图通过 View 检查这个,但它总是给我 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

回答by Sujit

Creating Session:

创建会话:

$newdata = array(
               'username'  => 'johndoe',
               'email'     => '[email protected]',
               '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
}

回答by ravi patel

 if ($this->session->userdata('variable') !== FALSE) {
  echo 'Variable is set';
} else {
  echo 'Variable is not set';
}  

More info

更多信息

Demo code

演示代码

回答by antelove

Using has_userdata

使用 has_userdata

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

        return TRUE;       

    } else {

        return FALSE;     

    }