Search code examples
phpcodeignitersessionconditional-statementsis-empty

CodeIgniter 3 - Session item getter with PHP empty function


I've just noticed something weird using CodeIgniter 3 session system and I'm wondering if it's an issue or just something normal with PHP.

To explain, I have this variable initialized :

$this->session->connected_client_id = 9;

When I'm doing this :

$id = $this->session->connected_client_id
// Testing using "get_userdata" function
if (empty($this->session->get_userdata('connected_client_id'))) {
    echo "EMPTY $id";
} else {
    echo "NOT EMPTY $id";
}

It's ok, I'm getting : NOT EMPTY 9

BUT, when I'm doing this :

$id = $this->session->connected_client_id
// Testing using the CodeIgniter 3 session getter
if (empty($this->session->connected_client_id))) {
    echo "EMPTY $id";
} else {
    echo "NOT EMPTY $id";
}

It's NOT ok, I'm getting : EMPTY 9

While when I'm doing this :

$id = $this->session->connected_client_id
// Testing using a variable as intermediate from the CI3 session getter
if (empty($id))) {
    echo "EMPTY $id";
} else {
    echo "NOT EMPTY $id";
}

It's ok, I'm getting : NOT EMPTY 9

I'm using a variable as intermediate from the previous getter that was returning "EMPTY 9" ...
Does anyone have an explanation to this ? And is there a proper way to achieve this check without this "empty trouble" ?


Solution

  • It's ... both - normal in PHP given the CI_Session class code, but also an issue in CodeIgniter because this particular use case should work but doesn't.

    This patch will fix it in the next CodeIgniter version (3.0.6): https://github.com/bcit-ci/CodeIgniter/commit/2c10f60586faf59b9380608c5a9bf01ff2522483

    However, I'm inclined to suggest accessing the $_SESSION array directly - that's what the library gives you anyway.