How do check if a PHP session is empty?

后端 未结 8 1001
無奈伤痛
無奈伤痛 2020-12-02 15:50

Is this bad practice?

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

Is there a way to check if its empty or

相关标签:
8条回答
  • 2020-12-02 15:53

    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.

    0 讨论(0)
  • 2020-12-02 15:54

    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');
             } 
    
    0 讨论(0)
  • 2020-12-02 15:55

    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)

    0 讨论(0)
  • 2020-12-02 15:57
    if(isset($_SESSION))
    {}
    else
    {}
    
    0 讨论(0)
  • 2020-12-02 15:59

    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'] == '')
    
    0 讨论(0)
  • 2020-12-02 16:02

    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).
    0 讨论(0)
提交回复
热议问题