How do check if a PHP session is empty?


Is this bad practice?

if ($_SESSION['something'] == '')
    echo 'the session is empty';

Is there a way to check if its empty or it is not set? I'm actualy doing this:

if (($_SESSION['something'] == '') || (!isset($_SESSION['something'])) {
    echo 'the session is either empty or doesn\'t exist';

Does !isset just checks if a $_SESSION[''] exist and doesn't check if, is there are values in the array or not

5/4/2013 11:48:27 AM

Accepted Answer

I would use isset and empty:

if(isset($_SESSION['blah']) && !empty($_SESSION['blah'])) {
   echo 'Set and not empty, and no undefined index error!';

array_key_exists is a nice alternative to using isset to check for keys:

if(array_key_exists('blah',$_SESSION) && !empty($_SESSION['blah'])) {
    echo 'Set and not empty, and no undefined index error!';

Make sure you're calling session_start before reading from or writing to the session array.

12/31/2017 7:25:31 AM

Use isset, empty or array_key_exists (especially for array keys) before accessing a variable whose existence you are not sure of. So change the order in your second example:

if (!isset($_SESSION['something']) || $_SESSION['something'] == '')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow