What is the proper way to test CodeIgniter session variable?

半腔热情 提交于 2019-12-22 09:36:24

问题


Take the following code snippet. What is the best way to test to make sure the session variable isn't empty?

<?php if ($this->session->userdata('userID')) {
   $loggedIn = 1;
}
else {
   $loggedIn = 0;
} ?>

If later in my script, I call the following, the first prints properly, but on the second I receive Message: Undefined variable: loggedIn

<?php echo $this->session->userdata('userID'));
      echo $loggedIn; ?>

I've tried using !empty and isset, but both have been unsuccessful. I also tried doing the if/then statement backwards using if (!($this->session->userdata('userID')), but no dice. Any thoughts?


回答1:


Try doing the following instead:

<?php 
$loggedIn = 0;
if ($this->session->userdata('userID') !== FALSE) {
   $loggedIn = 1;
}
?>

If the error continues, you'll need to post more code in case you're calling that variable in another scope.




回答2:


If your aim is to see whether or not the session variable 'userID' is set, then the following should work:

$this->session->userdata('userID') !== false



回答3:


Why don't you create a boolean field in your session called is_logged_in and then check like:

if(false !== $this->session->userdata('is_logged_in'))



回答4:


if($this->session->userdata('is_logged_in')) {
    //then condition
}

This is the proper way to test!



来源:https://stackoverflow.com/questions/10712250/what-is-the-proper-way-to-test-codeigniter-session-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!