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

May 06, 2020 am 07:46 AM
cookie session

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();
Copy after login

, 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
Copy after login

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();
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

What are the differences between JavaScript and PHP cookies? What are the differences between JavaScript and PHP cookies? Sep 02, 2023 pm 12:29 PM

JavaScriptCookies Using JavaScript cookies is the most effective way to remember and track preferences, purchases, commissions and other information. Information needed for a better visitor experience or website statistics. PHPCookieCookies are text files that are stored on client computers and retained for tracking purposes. PHP transparently supports HTTP cookies. How do JavaScript cookies work? Your server sends some data to your visitor's browser in the form of a cookie. Browsers can accept cookies. If present, it will be stored on the visitor's hard drive as a plain text record. Now, when a visitor reaches another page on the site

How cookies work How cookies work Sep 20, 2023 pm 05:57 PM

The working principle of cookies involves the server sending cookies, the browser storing cookies, and the browser processing and storing cookies. Detailed introduction: 1. The server sends a cookie, and the server sends an HTTP response header containing the cookie to the browser. This cookie contains some information, such as the user's identity authentication, preferences, or shopping cart contents. After the browser receives this cookie, it will be stored on the user's computer; 2. The browser stores cookies, etc.

Detailed explanation of where browser cookies are stored Detailed explanation of where browser cookies are stored Jan 19, 2024 am 09:15 AM

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

See all articles