How can I clear my php session data correctly?

后端 未结 3 780
离开以前
离开以前 2020-12-11 16:44

My php website flows like this:

  • Page1.php has an html form which POSTs to Page2.php
  • Page2.php stores all the POST data into SESSION variables and has
相关标签:
3条回答
  • 2020-12-11 17:00

    Use session_unset(). Like this:

    <?php session_start(); ?><!DOCTYPE html>
    <html>
      <body>
        <?php
          $_SESSION["variabletounset"] = "I am going to be unset soon along with all of the other session variables.";
          print '<pre>' . "\n";
          print_r($_SESSION);
          print '    </pre>' . "\n";
    
          session_unset();
    
          print '    <pre>' . "\n";
          print_r($_SESSION);
          print '    </pre>' . "\n";
        ?>
      </body>
    </html>
    

    This would output:

    Array
    (
    variabletounset => I am going to be unset soon along with all of the other session variables.
    )
    
    Array
    (
    )
    
    0 讨论(0)
  • 2020-12-11 17:04

    From the documentation:

    If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used,
    use unset() to unregister a session variable, i.e. unset ($_SESSION['varname']);
    

    And take care about session_destroy:

    session_destroy destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session

    0 讨论(0)
  • 2020-12-11 17:06

    Only use session_unset() for older deprecated code that does not use $_SESSION.

    see session_destroy manual

    example you can try and see how it works

    session.php

    <?php
    session_start();
    $_SESSION = array('session1'=>1,'session2'=>2);
    
    echo $_SESSION['session1']; //1
    $_SESSION['session1'] = 3;
    echo "<pre>";
    print_r($_SESSION); //session one now updated to 3
    echo "</pre>";
    
    
    $_SESSION = array();
    if ($_SESSION['session1']) {
     echo $_SESSION['session1']; //  IS NOW EMPTY
    } else {
     echo "woops... nothing found";
    }
    ?>
    <p>
    <a href="destroyed.php">NOW GOING TO DESTROYED PHP<a/>
    </p>
    
    <?php
    session_destroy();
    ?>
    

    destroyed.php

    <?php
    session_start(); // calling session start first on destroyed.php
    
    print_r($_SESSION); // prints Array ( )  
    ?>
    
    0 讨论(0)
提交回复
热议问题