How do check if a PHP session is empty?
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.
you are looking for PHP’s empty()
function
You could use the count() function to see how many entries there are in the $_SESSION array. This is not good practice. You should instead set the id of the user (or something similar) to check wheter the session was initialised or not.
if( !isset($_SESSION['uid']) )
die( "Login required." );
(Assuming you want to check if someone is logged in)
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'] == '')