What is a Session?
In Web application development, the session is called a conversation. is primarily used to save data for a visitor.
Because of the HTTP stateless features, the server will not remember the client, on the server side, each request is completely new.
So, how does the server know which visitor is asking for it? How do you map different data to the right visitors? The answer is to give the visitor a unique ID that gets the data in the Session.
For example: When we go shopping in the supermarket, we are not allowed to bring items into the store by the security guard, we must store the items in the supermarket storage box. We gave him the item, how he knew who it was, and he gave us a different key. When we want to take our items, open the corresponding box with a unique key.
Like the above analogy, the Session can be understood as the "box" that holds our data, and of course, these "boxes" are on the service side. The server gives the visitor the only "key", which is called session_id. With their own session_id, visitors can get their own server-side data.
SESSION_ID is passed to the visitor (client) in two ways: URL or cookie. For details see: Transfer session ID
What does Session and Cookie matter
cookie is also a technology generated by the HTTP stateless features. It is also used to save the visitor's identity and some data. Each time the client initiates an HTTP request, it adds the Cookie data to the HTTP header and submits it to the server. This allows the server to know the visitor's information based on the content of the Cookie. The
can be said that the session and the Cookie do similar things, but the session is to save the data on the server, through the client-submitted session_id to obtain the corresponding data, and the cookie is to save the data on the client, Submits the data to the server each time the request is initiated.
As mentioned above, session_id can be passed by URL or cookie, because the URL is more insecure and inconvenient to use than the cookie, so it is generally a cookie to pass session_id.
The server generates session_id, which is sent to the client via HTTP messages (such as a browser), and the client receives the instructions to create a cookie that holds the session_id. Cookies are stored in the form of Key/value, which looks something like this: PHPSESSID=e4tqo2ajfbqqia9prm8t83b1f2
. In PHP, the name of the cookie that holds session_id is called by default PHPSESSID
, which can be modified by php.ini session.name
or by a function session_name()
.
Why not recommend using the files-type Session processor that comes with PHP
In PHP, the default session processor is files
that the processor can be implemented by the user itself (see: Custom Session Manager). I know there are many mature Session processors: Redis, Memcached, MongoDB ...
Why is it not recommended to use the files type processor that comes with PHP, which is given in the official PHP manual:
Either by calling the function session_start () to open the session manually or by using the configuration item Session.auto_start to automatically open the session, for file-based session data saving (the default behavior of PHP), the session data file is locked at the beginning of the session. Until the PHP script finishes or explicitly calls Session_write_close () to save the session data. During this time, other scripts do not have access to the same session data file.
Refer to the following: basic usage of Session
To prove this, let's Create 2 files:
Files: session1.php
<?phpsession_start (); sleep (5); Var_dump ($_session);? >
Files: session2.php
<?phpsession_start (); Var_dump ($_session);? >
http://127.0.0.1/session1.php , and then immediately access http://127.0.0.1/session2.php
in the new tab of the current browser. The experiment found that session1.php waited 5 seconds for output, and session2.php waited for nearly 5 seconds to output. A separate access to session2.php is second. Access the session1.php in one browser and then immediately access the session2.php in a different browser. The result is that session1.php waits 5 seconds for output, while session2.php is seconds away.
Analyze the cause of this: in the example above, the cookie is used by default to pass session_id, and the scope of the cookie is the same. In this way, the 2 addresses are accessed in the same browser, and the session_id submitted to the server is the same (to mark the visitor, which is the effect we expect). When accessing session1.php, PHP saves the path to the session file on the server according to the submitted session_id (default is /tmp
, through in php.ini; Session.save_path
or function session_save_path ()
to modify) finds the corresponding session file and locks it. If you do not explicitly call , session_write_close ()
, the file lock will not be released until the current PHP script finishes executing. If there is a time-consuming operation in the script (such as in the example, sleep (5)
), then another request that holds the same session_id is forced to wait because the file is locked, so there is a request blocking situation.
In this case, after using the Session, immediately display the call session_write_close()
is not solve the problem? For example, the sleep(5)
previous call session_write_close()
.
Indeed, such session2.php will not be blocked by session1.php. However, displaying the call session_write_close()
means writing the data to a file and ending the current session. Then, you must call back when you want to use the Session in the following code session_start()
.
For example:
<?phpsession_start (); $_session[' name '] = ' Jing '; var_dump ($_session); Session_write_close (); sleep (5); session_ Start (); $_session[' name '] = ' mr.jing '; var_dump ($_session);? >
The official scheme:
This can be a serious problem for a large number of sites that use Ajax or concurrent requests. The simplest way to solve this problem is if you modify the variables in the session, you should call Session_write_close () as soon as possible to save the session data and release the file lock. Another option is to replace the file session Save manager with a session save manager that supports concurrent operations.
The way I recommend it is to use Redis as the processor for the Session.
Expand reading:
Why can't I store Session with memcached
How to use Redis as a PHP Session handler
When was the Session data deleted?
This is a question that is often asked by the interviewer.
First look at the instructions in the Official Handbook:
session.gc_ Maxlifetime
Specifies the number of seconds after which data is considered "junk" and purged. Garbage collection may start when the session starts (depending on session.gc_probability
and session.gc_divisor
). session.gc_probability
session.gc_divisor
together to manage GC (garbage Collection garbage collection) The probability of the process starting. This probability is calculated by Gc_probability/gc_divisor. For example, 1/100 means that there is a 1% probability of starting the GC process in each request. session.gc_probability
defaults to 1, session.gc_divisor
defaults to 100.
Keep using the less appropriate analogy above: if we put the items in the store in the supermarket and don't take them away, after a long time (say, one months), the security guard will clean up the items in the storage boxes. Of course not over the deadline security will come to clean up, maybe he is lazy, or he did not think of this thing.
Take a look at the references to the two sections of the handbook:
If you use the default file-based session processor, the file system must maintain tracking access time (Atime). The Windows FAT file system does not work, so if you have to use the FAT file system or other file systems that cannot track atime, then you have to think of another way to handle the garbage collection of session data. Since PHP 4.2.3 Mtime (modified time) to replace the atime. So there's no problem with file systems that can't track atime.
GC run time is not accurate, with a certain probability, so this setting does not ensure that the old session data is deleted. Some session store processing modules do not use this setting item.
I am doubtful about this kind of deletion mechanism.
For example, if the gc_probability/gc_divisor is set to a larger size, or if the request volume of the website is larger, the GC process will be started more frequently.
Also, after the GC process starts, it is necessary to traverse the Session file list, compare the file modification time and the current time of the server, determine whether the file expires and decide whether to delete the file.
That's why I don't think I should be using the files-type Session processor that comes with PHP. Redis or Memcached is inherently supportive of the key/value expiration mechanism and is suitable for use as a session processor. or implement a file-based processor yourself, and determine whether the file expires when the corresponding single session file is obtained according to SESSION_ID.
Why the Session data will not be taken after restarting the browser
session.cookie_lifetime
The lifetime of the cookie sent to the browser is specified in seconds. A value of 0 means "until the browser is closed." The default is 0.
In fact, the session data is not deleted (it is also possible that the probability is relatively small, see the previous section). Just close the browser, save the session_id Cookie is gone. That means you lost the key to opening the grocery store box (session_id).
In the same vein, browser cookies are manually erased or other software is removed to create this result.
Why the browser is open, I have been logged out for a long time without operation
This is called "anti-Stay", in order to protect the user account security.
This section is put in because the implementation of this function may be related to the deletion mechanism of the session (it is possible, because this function does not have to be implemented in the session, also can be implemented with cookies).
To put it simply, there is no operation for a long time, the Session file expiration of the server is deleted.
An interesting thing.
Also, found that the session file is deleted, again request, or will generate the same as the previous file name of the session (because the browser is not closed, the request sent again session_id is the same, so the re-generated session file filename is the same). However, I do not understand is: this re-emergence of the creation of the file is the first time that the creation time, is it from the Recycle Bin back? (Yes, I did this experiment in the window.)
The reason I'm guessing is this: when the session is started, PHP finds and opens the corresponding session file based on session_id before it starts the GC process. The GC process only checks for files other than the current Session file, and finds out that it is out of date. All, even if the current Session file has expired, the GC has not deleted it.
I think this is unreasonable.
Since this is not a significant impact (after all, there is a lot of online requests, the current request of expired files by other requests aroused by the GC to kill the likelihood is relatively large) + I do not have the confidence to see PHP source code + I am not online using PHP's own files-type Session processor. Therefore, I have not studied this problem in depth. Please understand.
The <?php//expiration time is set to 30 seconds Ini_set (' session.gc_maxlifetime ', ' + ');//GC start probability is set to 100%ini_set (' session.gc_probability ', ' (' Session.gc_divisor ', ' ini_set '); Session_Start (); $_session[' name '] = ' Jing '; var_dump ($_session);? >
Expand reading:
How to set a Session with a strict 30-minute expiration date
Some questions about the Session in PHP