Is this bad practice?
if ($_SESSION[\'something\'] == \'\')
{
echo \'the session is empty\';
}
Is there a way to check if its empty or
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.
I know this is old, but I ran into an issue where I was running a function after checking if there was a session. It would throw an error everytime I tried loading the page after logging out, still worked just logged an error page. Make sure you use exit(); if you are running into the same problem.
function sessionexists(){
if(!empty($_SESSION)){
return true;
}else{
return false;
}
}
if (!sessionexists()){
redirect("https://www.yoursite.com/");
exit();
}else{call_user_func('check_the_page');
}
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)
if(isset($_SESSION))
{}
else
{}
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'] == '')
If you want to check whether sessions are available, you probably want to use the session_id() function:
session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).