Location>code7788 >text

Session operation mechanism

Popularity:920 ℃/2024-08-31 11:45:20

How sessions are stored

By default it will be stored in the temporary directory of the server as a file with the name (sess_+session_id), these can be configured in the file, the contents of the file are serialized data as follows:

$_SESSION['name'] = ‘John Doe'
$_SESSION['age'] = 18
The session file is:
    name|i:ZhangSan;age|i:18

The following is the commonly used configuration related to sessionde in the file:

session.save_handler = files #Specify how to store the session, default is files, can also be redis or memcache, to improve efficiency
session.save_path= "d:/wamp/tmp"    # Specify the storage directory for session files
session.use_cookies= 1    #Whether to use cookies to store session_id
= PHPSESSID # session name where client stores session_id
session.auto_start= 0    #Whether to enable session automatically
session.cookie_lifetime= 0    # Set the expiration time of the session_id stored in the client, note that the expiration time of the session is intervals, such as the expiration time of 20 minutes, re-access, the expiration time of the session will be recalculated, the expiration time of the cookie is accumulative.
session.serialize_handler= php
session.gc_divisor = 1000
session.gc_probability = 1
session.gc_maxlifetime = 1440    #set upsessionExpiry time of documents

The garbage collection mechanism of session

A user to access the server will generate a session file, close the browser, and then access the server will generate a new session file, so that the session of the garbage file will be a lot of long time not to clean up will take up a lot of disk space, access to the session file of the speed will be reduced, the gc process garbage collection is very necessary!
First, I'll mention some of PHP's session cleanup functions.

unset($_SESSION['name']) clears a variable
session_unset() passes no arguments, and clears all session variables, but the session file remains.
session_destroy() clears the session file.
setcookie(session_name(),'', time()-1000, '/')    set upcookieExpired documents

Note: Generally after doing session_destroy() operation, setcookie(session_name(),'', time()-1000, '/') is also required, otherwise the user refreshes the page and the same session_id is set again, generating the session file

Then it's gc that automatically deletes the junk files:

session.gc_divisor = 1000
session.gc_probability = 1
session.gc_maxlifetime = 1440    #set upsessionExpiry time of documents

The probability of deleting the session garbage file is, session.gc_probability/session.gc_divisor=1/1000, which means that there is a 1/1000 probability of triggering the gc process each time session_start() is executed, but there must be one time out of 1000, if session .gc_probalility= 1000That's 100% probability, which means that every session_start() triggers the gc process