search
HomeBackend DevelopmentPHP TutorialUnderstand Session in PHP and control the Session validity period, session validity period_PHP tutorial

Understand Session in PHP and control of Session validity period. Session validity period

0. What is session?
The Chinese translation of Session is called "conversation". Its original meaning refers to a series of actions/messages that have a beginning and an end. For example, when making a phone call, the series of processes from picking up the phone to dialing to hanging up the phone can be called a session. The current understanding of sessions in society is very confusing: sometimes we can see the words "During a browser session,...", where the session refers to the period from the opening to closing of a browser window; you can also see When referring to the sentence "the user (client) during a session", it may refer to a series of actions of the user (usually a series of actions related to a specific purpose, such as from logging in to purchasing goods to checking out. Such an online shopping process; however, sometimes it may only refer to a connection; the difference can only be inferred from the context
However, when the word session is associated with a network protocol, it often implies two meanings: "connection-oriented" and/or "state-maintaining". "Connection-oriented" means that the communicating parties must first establish a connection before communicating. A communication channel, such as a phone call, cannot begin until the other party answers the phone. "Maintaining status" means that the communicating party can associate a series of messages so that the messages can depend on each other. For example, a waiter can recognize an old customer who comes again and remember that the customer owed the store a dollar last time. . Examples of this category are "a TCP session" or "a POP3 session".
In view of the fact that this confusion is irreversible, it is difficult to have a unified standard to define session. When reading session-related information, we can only rely on context to infer understanding. But we can understand it this way: For example, when we make a phone call, from the moment the call is made to the moment we hang up, the phone remains connected, so this connected state is called session. It is a public variable that always exists during the interaction between the visitor and the entire website. When the client does not support COOKIE, in order to ensure that the data is correct and safe, the SESSION variable is used. Visitors to the website are assigned a unique identifier, a so-called session ID. It is either stored in a client-side cookie or passed via the URL.
The invention of SESSION filled the limitations of the HTTP protocol: the HTTP protocol is considered a stateless protocol and cannot know the user's browsing status. When it completes the response on the server side, the server loses contact with the browser. This is consistent with the original purpose of the HTTP protocol. The client only needs to simply request the server to download certain files. Neither the client nor the server needs to record each other's past behavior. Each request is independent. It's like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket.
Therefore, the user's relevant information is recorded through SESSION (cookie is another solution), so that the user can confirm when making a request to the web server again as this identity. The invention of sessions allows a user to preserve his or her information when switching between multiple pages. Website programmers all have this experience. The variables in each page cannot be used in the next page (although form and url can also be implemented, but these are very unsatisfactory methods), while the variables registered in SESSION are Can be used as a global variable.
​ ​ So what is the use of SESSION? Everyone has used the shopping cart when shopping online. You can add the products you choose to the shopping cart at any time, and finally go to the checkout counter to check out. During the entire process, the shopping cart has been playing the role of temporarily storing the selected products. It is used to track the user's activities on the website. This is the role of SESSION. It can be used for user identity authentication, program status recording, and between pages. Parameter passing, etc.
COOKIE technology is used in the implementation of SESSION. SESSION will save a COOKIE containing session_id (SESSION number) on the client side; other session variables, such as session_name, etc., will be saved on the server side. When the user requests the server, the session_id is also sent to the server. By extracting the variables saved on the server side through the session_id, you can identify who the user is. At the same time, it is not difficult to understand why SESSION sometimes fails.
When the client disables COOKIE (click "Tools" - "internet="">Internet Options" in IE, click "Security" - "Custom Level" item in the pop-up dialog box, and change "Allow each conversation" COOKIE" is set to disabled), session_id will not be passed, and SESSION will be invalid at this time. However, php5 can automatically check the cookie status on the Linux/Unix platform. If the client is disabled, the system will automatically append the session_id to the URL and pass it. Windows hosts do not have this function. 

1.php session validity period

The default session validity period of PHP is 1440 seconds (24 minutes). If the client does not refresh for more than 24 minutes, the current session will be recycled and invalid.
When the user closes the browser, the session ends and the session becomes invalid.

You can modify session.gc_maxlifetime in php.ini to set the session life cycle, but there is no guarantee that the session information will be deleted immediately after this time is exceeded. Because GC is started based on probability, it may not be started for a long time. Then a large number of sessions are still valid after exceeding session.gc_maxlifetime.


2.session.gc_maxlifetime,session.gc_probability,session.gc_divisor description

session.gc_maxlifetime = 30 means that when the session file is not accessed after 30 seconds, it is considered an expired session and is waiting for GC recycling.

The probability of GC process call is calculated through session.gc_probability/session.gc_divisor, and session.gc_divisor defaults to 1000,
If session.gc_probability = 1000, then the GC process will be called every time session_start() is executed to perform recycling.

Increasing the probability of session.gc_probability/session.gc_divisor will help, but it will have a serious impact on performance.


3. Strictly control session expiration methods

(1). Use memcache/redis to save the session and set the expiration time. Because the recycling mechanism of memcache/redis is not based on probability, it can ensure that the session will become invalid after expiration.

(2). Only use PHP to implement it, create a session class, and write the expiration time when the session is written. When reading, determine whether it has expired based on the expiration time.

<&#63;php
/**
 * Session控制类
 */
class Session{

  /**
   * 设置session
   * @param String $name  session name
   * @param Mixed $data  session data
   * @param Int  $expire 超时时间(秒)
   */
  public static function set($name, $data, $expire=600){
    $session_data = array();
    $session_data['data'] = $data;
    $session_data['expire'] = time()+$expire;
    $_SESSION[$name] = $session_data;
  }

  /**
   * 读取session
   * @param String $name session name
   * @return Mixed
   */
  public static function get($name){
    if(isset($_SESSION[$name])){
      if($_SESSION[$name]['expire']>time()){
        return $_SESSION[$name]['data'];
      }else{
        self::clear($name);
      }
    }
    return false;
  }

  /**
   * 清除session
   * @param String $name session name
   */
  private static function clear($name){
    unset($_SESSION[$name]);
  }

}
&#63;>

demo:

<&#63;php
session_start();

$data = '123456';
session::set('test', $data, 10);
echo session::get('test'); // 未过期,输出
sleep(10);
echo session::get('test'); // 已过期
&#63;>

Articles you may be interested in:

  • Detailed explanation of PHP session settings (expiration, invalidation, validity period)
  • Think about solutions to invalid session and cookie in PHP
  • Solution to invalid php session verification
  • PHP session validity session.gc_maxlifetime
  • PHP session validity problem

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1089947.htmlTechArticleUnderstand the Session in PHP and control the Session validity period. The session validity period is 0. What is a session? The Chinese translation of Session is "conversation", and its original meaning refers to a series that has a beginning and an end...
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
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.