Understand the session in PHP and the control of session expiration _php skills

Source: Internet
Author: User

0. What is session?
The Chinese translation of the session is called "conversation", whose meaning is a series of actions/messages from the beginning to the end, such as calling from the phone to the telephone to hang up the phone in the middle of a series of processes can be called a sessions. At present, the understanding of the session in the community is very confusing: sometimes we can see the words "during a browser session, ...", where the conversation is from a browser window open to the end of this period, you can also see the "User (client) during a session" such a sentence, It may refer to a series of actions by a user (typically a sequence of actions related to a specific purpose, such as a process of online shopping from login to purchase to checkout; however, sometimes it may just be a connection; the difference can only be inferred by context.)
However, when the term session is associated with a network protocol, it also tends to imply 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 communication channel, such as telephone, until the other side of the telephone communication to start. "Staying state" means that one side of the communication can associate a series of messages so that the messages can be interdependent, such as a waiter who can recognize the old customer again and remember that the last time the customer owed the store a dollar. Examples in this category are "one TCP session" or "one POP3 session".
Given that this confusion is immutable, it is difficult to define a uniform standard for the session to be defined. And in reading the session-related material, we can only infer the understanding by context. However, we can understand this: for example, we call, from the moment of dialing to hang up the phone, because the phone is always connected to the state, so the status of this switch is called session. It is the visitor and the entire website interaction process always exists the public variable, when the client does not support the cookie, in order to guarantee the data to be correct, the security, uses the session variable. Visitors to the site are assigned a unique identifier, known as the session ID. It is either stored on the client's cookie or passed through the URL.
The session's invention fills in the limitations of the HTTP protocol: the HTTP protocol is considered a stateless protocol, and the user's browsing status is not known, and the server loses contact with the browser when it completes its response on the service side. This is consistent with the HTTP protocol's original purpose, the client simply needs to download some files to the server, whether the client or the server does not 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-member) hypermarket.
As a result, the user's information is logged by session (cookie is an alternative solution) for the user to confirm when requesting the Web server again in this capacity. The invention of the session allows a user to save his information when switching between multiple pages. Website programmers have the experience that the variables on each page can not be used on the next page (although Form,url can also be implemented, but this is a very unsatisfactory way), and session of the registered variables can be used as a global variable.
So what is the use of the session? When shopping on the Internet, everyone has used a shopping cart, you can always add the goods you buy to the shopping cart, and finally go to the cashier checkout. Throughout the process, the shopping cart has been playing the role of temporary storage of selected goods, using it to track the activities of users on the site, this is the role of the session, it can be used for user identity authentication, program status records, transfer between the parameters of the page.
In the implementation of the session, cookie technology is used to save a cookie containing the session_id on the client, and to save additional session variables on the server side, such as Session_name and so on. When the user requests the server also sends the SESSION_ID together to the server, through session_id extracts is saved on the server side the variable, 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" in IE-"internet=" ">internet Options"), click the "Security"-"Custom Level" entry in the pop-up dialog box to set "Allow each dialog cookie" to be disabled, session_ The ID will not be delivered, and the session is invalid at this time. However, PHP5 can automatically check the cookie status on the Linux/unix platform, and if the client is set to disable, the system automatically attaches the session_id to the URL for delivery. The Windows host does not have this capability.

1.php Session Validity

PHP's session expiration date is 1440 seconds (24 minutes), and if the client does not refresh for more than 24 minutes, the current sessions 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 lifecycle, but it does not guarantee that the session information will be deleted immediately after this time. Because the GC is started on a probability basis, 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 and is waiting for GC collection.

The probability of a GC process call is computed by session.gc_probability/session.gc_divisor, and Session.gc_divisor defaults to 1000,
If session.gc_probability = 1000, then the GC process is invoked every time the session_start () is executed, and the recycle is performed.

Increasing the chance of session.gc_probability/session.gc_divisor can be helpful, but it can have a serious impact on performance.


3. Strict control session expiration method

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

(2). Use only the PHP implementation, create a session class, when the session writes, 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 Timeout (sec) *
   /
  Public The 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;
  }

  /**
   * Clears session
   * @param String $name Session name
   *
  /private static function Clear ($name) {
    Unset ($_session[$name]);
>

Demo

<?php
session_start ();

$data = ' 123456 ';
Session::set (' Test ', $data, ten);
echo session::get (' Test '); Not expired, output sleep
(ten);
echo session::get (' Test '); Has expired
?>

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.