Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to test CodeIgniter session variable?

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?

like image 882
JamieHoward Avatar asked Jun 09 '26 00:06

JamieHoward


2 Answers

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.

like image 74
Aaron W. Avatar answered Jun 10 '26 15:06

Aaron W.


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
like image 25
c.hill Avatar answered Jun 10 '26 16:06

c.hill