


PHP session control: in-depth understanding of the differences and usage between cookies and sessions
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.
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([ 'cookie_lifetime' => 3600, 'gc_maxlifetime' => 3600 ]); if (isset($_SESSION['lifetime']) && $_SESSION['lifetime'] > time()) { // 未过期,更新session的lifetime及cookie的有效期 $_SESSION['lifetime'] += 3600; $tmpVal = $_COOKIE[session_name()]; setcookie(session_name(), $tmpVal, time() + 3600, '/'); } else { // 过期删除 $_SESSION = []; if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 100, '/'); } 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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software