Understand the session in PHP and control the duration of the session, session validity _php Tutorial

Source: Internet
Author: User
Tags php session

Understand the session in PHP and control the duration of the session, session validity


0. What is a session?
The Chinese translation of the session is called "conversation", its original meaning refers to the beginning and end of a series of actions/messages, such as phone calls from the pick up the telephone to hang up the phone in the middle of a series of processes can be called a session. At present, the community's understanding of the session is very confusing: sometimes we can see the words "during a browser session, ...", where the session is opened from a browser window to close this period, you can also see "User (client) during a session," the word, It may refer to a series of actions by a user (typically a series of actions related to a specific purpose, such as a process of online shopping from login to purchase to checkout), but sometimes it may simply mean a connection; the differences can only be inferred by context.
However, when the term session is associated with a network protocol, it often implies a "connection-oriented" and/or "hold State" two meanings, "connection-oriented" refers to the communication between the two parties before the communication to establish a channel of communication, such as the telephone, until the other side of the phone communication to start. "Hold state" means that the party of communication can associate a series of messages, so that the message can be interdependent, such as a waiter can recognize the return of the old customers and remember the last time the customer owed a money in the store. Examples of this type are "a TCP session" or "a POP3 session."
Given that this confusion is immutable, it is difficult to define the session in a uniform standard. When reading the session, we can only infer the understanding by the context. However, we can understand this: for example, we call, from the moment we dial to hang up the phone, because the phone has been kept connected, so the status of this connection is called the session. It is a public variable that always exists during the interaction between the visitor and the entire website, and the session variable is used to ensure the data is correct and secure when the client does not support cookies. Visitors to the site are assigned a unique identifier, the so-called session ID. It is either stored on the client's cookie or passed through the URL.
The invention of the session fills the limits of the HTTP protocol: the HTTP protocol is considered a stateless protocol and the user's browsing state is not known, and the server loses contact with the browser after it has completed its response on the service side. This is consistent with the HTTP protocol's original purpose, and the client simply requests to download certain files to the server, neither the client nor the server need to record each other's past behavior, each request is independent, Like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket.
Therefore, the session (the cookie is another solution) records the user's information, so that the user again in this identity to the Web server to make a request for confirmation. The invention of the session allows a user to save his or her information while switching between multiple pages. Web programmers have this experience, the variables on each page cannot be used on the next page (although Form,url can also be implemented, but this is a very undesirable approach), and the variables registered in the session can be used as global variables.
So what's the use of the session? When shopping on the Internet, everyone has used a shopping cart, you can always add your purchases to the shopping cart, and then go to the cashier checkout. Throughout the process, the shopping cart has been playing the role of temporary storage of the selected products, using it to track the user's activity on the site, this is the role of the session, it can be used for user authentication, program status records, the parameters of the page transfer and so on.
In the implementation of the session using cookie technology, session will save a session_id (session number) in the client cookie, the server side to save other session variables, such as Session_name and so on. When the user requests the server also sends the session_id to the server, through session_id extracts the variable which is saved on the server side, can identify the user is who. It is also not difficult to understand why the session sometimes fails.
When the client disables cookies (click "Tools"-"internet=" ">internet options" in IE, click "Security"-"Custom Level" in the pop-up dialog to set "Allow each conversation cookie" to disabled), Session_ The ID will not be delivered, and the session is invalid at this time. However PHP5 on the Linux/unix platform can automatically check the cookie status, if the client is set to disable, the system automatically attaches the session_id to the URL to pass. The Windows host does not have this feature.

1.php Session Expiration Date

PHP session validity is 1440 seconds (24 minutes) By default, if the client does not refresh for more than 24 minutes, the current session will be recycled and invalidated.
When the user closes the browser, the session ends and the sessions expire.

You can modify the php.ini Session.gc_maxlifetime to set the session life cycle, but it is not guaranteed that the session information will be deleted immediately after this time. Because the GC is started by chance, it may not be started for a long time. So a lot of sessions are still valid after 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, waiting for GC to be reclaimed.

The probability of a GC process call is calculated by Session.gc_probability/session.gc_divisor, while session.gc_divisor defaults to 1000.
If session.gc_probability = 1000, the GC process is called every time the Session_Start () is executed, and the recycle is performed.

Raising the odds of Session.gc_probability/session.gc_divisor can help, but it can have a serious impact on performance.


3. Strict control of the session expiration method

(1). Use Memcache/redis to save the session, set the expiration time, because the Memcache/redis recovery mechanism is not by chance, can ensure that the session expires after the expiration.

(2). Use only PHP implementation, create a session class, when the session is written, the expiration time is also written. When read, determines whether it has expired based on the expiration time.

<?php/** * Session Control class */class session{  /**   * Set Session   * @param String $name  Session name   * @ Param Mixed $data  session Data   * @param Int  $expire Time Out (seconds)   *  /public static function set ($name, $ Data, $expire =600) {    $session _data = Array ();    $session _data[' data ' = $data;    $session _data[' expire ') = time () + $expire;    $_session[$name] = $session _data;  }  /**   * Read 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;  }  /**   * Clear Session   * @param String $name Session name   *  /private static function Clear ($name) {    Unset ($_session[$name]);}  ? >

Demo

<?phpsession_start (); $data = ' 123456 '; Session::set (' Test ', $data, ten); Echo session::get (' Test '); Not expired, output sleep (+), echo session::get (' Test '); Expired?>

Articles you may be interested in:

    • Detailed PHP Setup session (expiration, expiry, expiration)
    • Workarounds for invalid session and Cookie in thinkphp
    • Workaround for PHP validation session invalid
    • PHP Session Expiration Session.gc_maxlifetime
    • PHP Session Validity Issue

http://www.bkjia.com/PHPjc/1089947.html www.bkjia.com true http://www.bkjia.com/PHPjc/1089947.html techarticle understand the session in PHP and control the duration of the session, the session is valid for 0. What is a session? The Chinese translation of the session is called "conversation", its original meaning refers to the beginning of a series of ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.