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
You can check whether a variable has been set in a user's session using the function isset(), as you would a normal variable. Because the $_SESSION superglobal is only initialised once session_start() has been called, you need to call session_start() before using isset() on a session variable.
To determine if an item is present in the session, you may use the has method. The has method returns true if the item is present and is not null. To determine if an item is present in the session, even if its value is null, you may use the exists method.
In ancient history you simply needed to check session_id() . If it's an empty string, then session is not started. Otherwise it is.
I would use isset
and empty
:
session_start(); 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:
session_start(); 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With