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

后端 未结 9 454
耶瑟儿~
耶瑟儿~ 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:36

    You will have to delete the session records.

    if session handled by DB - delete the rows.

    if session handled by FILES - delete the files.

    here you can find full example:

    http://mdb-blog.blogspot.co.il/2015/05/php-destroydelete-all-sessions.html

    0 讨论(0)
  • 2020-11-27 18:40

    You should first know what sessions are: You can consider sessions as a data container on the server side that’s associated with a random identifier, the session ID. That session ID needs to be provided by the client so that the server can load the data associated to that session ID (and thus to that session) into the $_SESSION variable. Everything in that $_SESSION variable is also called session variables of the current active session.

    Now to your questions:

    Does the code will destroy all the sessions?? Is it the most common way? how do you guys destroy php sessions??

    The provided code just deletes the session data of the current session. The $_SESSION = array(); statement will simply reset the session variable $_SESSION so that a future access on the session variable $_SESSION will fail. But the session container itself is not deleted yet. That will be done by calling session_destroy.

    See also Truly destroying a PHP Session?

    Oh yeah, btw, what is that session_name()?? All session name? e.g $_SESSION['var1'], $_SESSION['var2']... ?

    The session_name is just used to identify the session ID parameter passed in a cookie, the URL’s query or via a POST parameter. PHP’s default value is PHPSESSID. But you can change it to whatever you want to.

    I dont need to use unset($_SESSION['var1']); any more right???

    No. The initial $_SESSION = array(); deletes all the session data.

    Whats the different between using session_destroy and unset($_SESSION[])??

    session_destroy will delete the whole session container while unset or resetting the $_SESSION variable will only delete the session data for the current runtime.

    0 讨论(0)
  • 2020-11-27 18:40

    To remove all session files from PHP, you can use this function:

    <?php
    /**
     * Hack to destroy all PHP session files
     *
     * @param string         $prefixSessionFile Prefix of the session filename
     * @param int|null|false $sessionIdLength   Expected Length of the session ID in the session filename. null: Determine automatically. false: do not check
     *
     * @return int Removed sessions
     * @throws Exception
     */
    function destroyAllPhpSessionFiles($prefixSessionFile = 'sess_', $sessionIdLength = 26)
    {
        if (session_status() === PHP_SESSION_DISABLED) {
            throw new Exception('Session handling is disabled');
        }
        if ($sessionIdLength === null) {
            if (session_status() !== PHP_SESSION_ACTIVE) {
                session_start();
            }
            $sessionIdLength = strlen(session_id());
        }
        // Allow to remove current session
        session_abort();
    
        // Get session dir
        if (!$sessionDir = session_save_path()) {
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                // Windows
                $sessionDir = sys_get_temp_dir();
                // If this script is called from a user (example in cmd), but your server uses the system environment variable (system-wide temp dir):
                //$sessionDir = system('echo %windir%') . DIRECTORY_SEPARATOR . 'Temp';
            } elseif (is_dir('/var/lib/php5')) {
                // Ubuntu or Debian
                $sessionDir = '/var/lib/php5';
            } elseif (is_dir('/var/lib/php/session')) {
                // RHEL or CentOS
                $sessionDir = '/var/lib/php/session';
            }
            if (!$sessionDir || !is_dir($sessionDir)) {
                $sessionDir = sys_get_temp_dir();
            }
        }
    
        // Drop session files
        $files           = scandir($sessionDir);
        $sessionsDeleted = 0;
        $prefixLength    = strlen($prefixSessionFile);
        $filenameLength  = $prefixLength + $sessionIdLength;
        foreach ($files AS $file) {
            if (substr($file, 0, $prefixLength) != $prefixSessionFile) {
                // Prefix does not fit
                continue;
            }
            if ($sessionIdLength && strlen($file) != $filenameLength) {
                // Filename length does not fit
                continue;
            }
            $path = $sessionDir . DIRECTORY_SEPARATOR . $file;
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                // Windows
                exec('DEL ' . $path);
            } else {
                // Linux / Unix
                shell_exec('rm -f ' . $path);
            }
            if (is_file($path)) {
                throw new Exception('Could not delete session file ' . $path);
            }
            $sessionsDeleted++;
        }
        return $sessionsDeleted;
    }
    
    0 讨论(0)
  • 2020-11-27 18:43

    session_name() is the name that's passed in the cookie / querystring. It's normally PHPSESSID but can be changed.

    There's no proper way to destroy all sessions. As @Marius says, you could try deleting the session files from session_save_path() but that's a hack at best.

    Alternatively you could use session_set_save_handler() to save your sessions to somewhere you have more control over, such as a database.

    0 讨论(0)
  • 2020-11-27 18:48

    If you want to avoid the warning:

    Warning: session_destroy(): Trying to destroy uninitialized session in ... on line 18

    Don't forget to add session_start(); to the beginning of your code. Other than that the code you provided works as intended.

    0 讨论(0)
  • 2020-11-27 18:52

    To destroy a single session, you should use the following:-

    session_destroy();
    

    Assuming you've used session_start() to previously start/resume a session.

    Destroying all sessions really depends on your setup, and how you're handling sessions.

    For most PHP installs, the session handling is done via files, so the best way would be to find the folder that keeps all the sessions (usually found from session_save_path()), and delete all the files under that.

    I think though, the best way to handle this might be to pre-emptively set a timestamp in each session you create. This means that you can then compare that timestamp to a set point (the time when you want to invalidate all sessions) and invalidate the session if it's before that time. This also means that you can do things like set a specific timeout for a session, etc etc.

    Another way might be to change to use Database Stored Sessions - you can find a good tutorial for this here

    0 讨论(0)
提交回复
热议问题