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

WBOY
Release: 2016-07-12 09:01:14
Original
1303 people have browsed it

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...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template