What is the correct way to check for a CodeIgniter session variable?

Take the following code snippet. What is the best way to verify that a session variable is not empty?

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

If later in my script, I call the following, the first prints correctly, but on the second I get the message: Undefined variable: loggedIn

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

I tried using !emptyand isset, but both of them were unsuccessful. I also tried to execute the if / then statement back using if (!($this->session->userdata('userID')), but not cubes. Any suggestions?

+3
source share
4 answers

Try the following:

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

If the error continues, you will need to send more code if you call this variable in another area.

+9
source

- , ​​ 'userID', :

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

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

if(false !== $this->session->userdata('is_logged_in'))
0
source
if($this->session->userdata('is_logged_in')) {
    //then condition
}

This is the right way to check!

0
source

All Articles