Is this a proper way to destroy all session data in php?

后端 未结 9 562
耶瑟儿~
耶瑟儿~ 2020-11-27 18:21

Got it from php.net, but I am not sure is this how everybody destroy all sessions?

// Unset all Sessions
$_SESSION = array();

if (isset($_COOKIE[session_nam         


        
9条回答
  •  自闭症患者
    2020-11-27 18:53

    The easiest way is not to delete all sessions at once, but to remember your last login and timestamp of the session reset.

    //Start your session
    session_start();
    
    //Get your stored timestamp of reset 
    //(i.e. stored in database)
    $timestamp_reset = ...
    
    //Get your stored timestamp of your session 
    //(i.e. store it in session or database when you log in)
    $timestamp_session = ...
    
    //See if the login was before the reset timestamp
    if ( $timestamp_reset > $timestamp_session ) {
        //Reset you session and go on
        session_unset();
    }
    

    It will not remove all session files, but will prevent old sessions running. And you do not have to rely on the garbage collector. Didn't find a similar answer here so I had to add this one. Have a nice day.

    To your further questions:

    Your code will only destroy your single session and is the most common way to i.e. sign out.

    session_name will give you the name of the variable, php uses for cookie exchange, you'll not need that most of the time. The code that is used in your example is a very old one, please do not use this.

    You do not have to unset every single array item by unset if you use session_destroy or session_unset.

    unset($_SESSION) will not work.

提交回复
热议问题