Table of Contents
Understand Session in PHP and control of Session validity period. Session validity period
Articles you may be interested in:
Home Backend Development PHP Tutorial Understand Session in PHP and control the Session validity period, session validity period_PHP tutorial

Understand Session in PHP and control the Session validity period, session validity period_PHP tutorial

Jul 12, 2016 am 09:01 AM
cookie php session

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;>

Copy after login

demo:

<&#63;php
session_start();

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

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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles