[php] 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

This question is related to php session

The answer is


The best practice is to check if the array key exists using the built-in array_key_exists function.


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).

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');
         } 

if(isset($_SESSION))
{}
else
{}

you are looking for PHP’s empty() function


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'] == '')

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)