Home >Backend Development >PHP Tutorial >PHP session control: in-depth understanding of the differences and usage between cookies and sessions

PHP session control: in-depth understanding of the differences and usage between cookies and sessions

齐天大圣
齐天大圣Original
2020-05-06 07:46:002378browse

Speaking of session control, most people will think, isn’t that simple? Isn’t it just COOKIE and SESSION?

It is indeed cookies and sessions, but do you really know how to use them?

I encountered a question like this during an interview a few years ago:

How to ensure that the session expires after 1 hour?

At that time, I thought this was not simple. Just set gc_maxlifetime to 3600. The interviewer at the time said that the answer was wrong and there was no guarantee that it would be invalid after one hour. Of course he didn't tell me the reason. Later, when I went back, I searched carefully and found out.

Before answering this question, let’s popularize the knowledge of cookies and sessions.

The difference and connection between COOKIE and SESSION

Differences in storage locations:

  • cookie storage On the client side

  • session is stored on the server side

The connection between them:

When the server opens the session , that is, after

session_start();

, a unique ID (session_id) will be generated and told to the client through the response header. After the client gets it, it will be saved in the cookie. When the client initiates a request again, it will bring this information. After receiving this information, the server will go to the directory where the session file is stored to find the corresponding file, and after finding it, it will extract the session information. It is through this mechanism that the server identifies the client's identity.

So, if there is no cookie, the session has no meaning.

After introducing the relationship between cookie and session, let’s talk about the validity period of session.

SESSION garbage collection

Generally, the default session validity period of PHP is 24 minutes. If the client has not issued a request after exceeding this time, it may trigger the garbage collection mechanism and delete expired session files. Why is it possible? This is about the principle of the garbage mechanism.

PHP's session garbage collection is probabilistic, and the probability is determined by session.gc_probability and session.gc_diviso. The probability is

session.gc_probability/session.gc_diviso

php's default gc_probability is 1, and gc_diviso's default is 100, which means that the probability of triggering garbage collection for each request is 1/100. Generally, when our website has a large number of visits, we can increase this probability, such as 1/1000, to reduce IO operations.

There is another point to note: For example, client A created a new session at this time (the session is valid for 10 minutes). After 8 minutes, A sent another request. At this time, will his session expire in 2 minutes or 10 minutes?

The answer is after 10 minutes. Because after the second request, the modification time of the session file on the server side also changed. Garbage collection looks at the last modification time of the session file. But think about it again, will the corresponding cookie validity period also be updated? Unfortunately, the cookie validity period will not be updated.

How to ensure that the session file will expire in one hour

Now, let’s look at the original question, how to ensure that the session file will expire in one hour. Session garbage collection is a probabilistic event, so you cannot count on it.

Then by setting the validity period of the cookie, can it be done by setting cookie_lifetime?

The answer is still no. The cookie is on the client side. It is gone. It is just that the cookie cannot be brought with the next request, but the corresponding session file still exists.

In fact, the simplest way to solve this problem is to save the session in redis, and use the expiration time of the redis key to ensure that it will expire within one hour. This method is also a recommended method

#But if you can only use PHP, how can it be done?

You can set a timestamp for each session, and determine the timestamp before each access. Paste the code:

<?php
session_start([
    &#39;cookie_lifetime&#39; => 3600,
    &#39;gc_maxlifetime&#39; => 3600
]);

if (isset($_SESSION[&#39;lifetime&#39;]) && $_SESSION[&#39;lifetime&#39;] > time()) {
    // 未过期,更新session的lifetime及cookie的有效期
    $_SESSION[&#39;lifetime&#39;] += 3600;
    $tmpVal = $_COOKIE[session_name()];
    setcookie(session_name(), $tmpVal, time() + 3600, &#39;/&#39;);
} else {
    // 过期删除
    $_SESSION = [];
    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), &#39;&#39;, time() - 100, &#39;/&#39;);
    }
    session_destroy();
}

After reading this content, I believe everyone should have a deeper understanding of PHP sessions.

The above is the detailed content of PHP session control: in-depth understanding of the differences and usage between cookies and sessions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn