简体   繁体   中英

How does PHP know when to delete a session?

I thought that sessions were stored on the client side because of the session getting deleted when the browser closes. However, today I've been told that this is not true and that the session is stored on the server.

So how does a session know when a browser was closed, so that the session gets deleted?

It doesn't. There are two factors at play:

  • the lifetime of the cookie on the client-side; This cookie contains the session ID. It does not have anything to do with the session data itself .

    The manual probably doesn't stress this enough:

    This has nothing to do with lifetime of a session

    Whatever you set this setting to, it won't change how long sessions live on your server.

    This only changes HTTP cache expiration time ( Expires: and Cache-Control: max-age headers), which advise browser for how long it can keep pages cached in user's cache without having to reload them from the server.

  • the lifetime of the session data on the server-side; The session is "activated" via a lookup with the session ID from the client. Its lifetime is controlled via session garbage collection settings discussed here .

    A commenter posted on the session.cache_expire documentation page, presumably actually talking about the session data:

    What most people also don't know, is that most Linux distributions (Debian and Ubuntu for me atleast) have a cronbjob that cleans up your session dir using the value set in the global /etc/php5/php.ini (which defaults to 24mins). So even if you set a value larger in your scripts, the cronbjob will still cleanup sessions using the global value.

    If you run into that situation, you can set the global value higher in /etc/php5/php.ini , disable the cronjob or even better, do your own session cleanup in a non-systemwide directory or a database.

    As you can see, confusing abounds amongst the community when making the distinction between session tracking and session data storage .

Session is identified by a cookie, which does get stored in the browser. It can have an expiry date/time, or it can be set to expire when the browser is closed. When the cookie expires, you can't identify your session storage any more, and the session is effectively expired. It does not get deleted unless the system admins or programmers specifically make a cleanup.

EDIT Just noticed the PHP tag. For how PHP cleans up its session files, check this question .

The server has no way of knowing when the browser is closed. Closing the browser will delete the session ID cookie from the client.

The session is deleted from the server once there are no requests in a given amount of time (the session timeout).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM