PHP--->cookie and session

Source: Internet
Author: User
Tags setcookie

Cookie and Sessioncookie and session understanding
  • The HTTP protocol itself is stateless, which is consistent with the HTTP protocol's original purpose, the client simply needs to request to the server to download some files, both the client and the server do 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-membership) hypermarket.
  • But the real business is the need for some authenticated users
  • Let's use a few examples to describe the difference and connection between a cookie and a session mechanism. I used to go to a coffee shop to drink 5 cups of coffee free of charge for a cup of coffee, but a one-time consumption of 5 cups of coffee is very little, then need some way to record a customer's consumption quantity. Imagine that there are actually no outside of the following scenarios:
    1, the shop staff is very powerful, can remember the amount of each customer's consumption, as long as the customer into the coffee shop, the clerk will know how to treat. This approach is the protocol itself that supports the state.
    2, issued to customers a card, which recorded the amount of consumption, there is generally a valid period. If the customer presents this card each time it is consumed, the consumption will be linked to the previous or subsequent consumption. This practice is to keep the state on the client.
    3, issued to the customer a membership card, in addition to the card number of what information is not recorded, each time the consumer, if the customer presented the card, then the shop clerk in the store records found this card number corresponding record add some consumer information. This is done by keeping the state on the server side.
    Since the HTTP protocol is stateless and is not expected to be stateful due to various considerations, the next two scenarios become a realistic choice. In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side. We also see that the session mechanism may need to use a cookie mechanism to save the identity, but in fact it has other options because the server-side hold-state scheme also needs to preserve an identity on the client side.

    Understanding Cookie Mechanism
  • The rationale for the
  • cookie mechanism is as simple as the example above, but there are several issues to be resolved: how to distribute the membership card, the content of the membership card, and how the customer uses the loyalty card.
    • Orthodox Cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header. However, purely client-side scripts such as JavaScript or VBScript can also generate cookies.
    • The use of cookies is automatically sent to the server in the background by the browser in a certain way. The browser checks all stored cookies and, if a cookie declares a scope greater than or equal to the location of the resource to be requested, sends the cookie to the server on the HTTP request header of the requesting resource. McDonald's membership card can only be presented in the McDonald's store, if a branch also issued their own membership card, then into the store in addition to show McDonald's membership card, but also to show the store's membership card.
    • If you do not set an expiration time, the cookie disappears when the browser window is closed, as long as the lifetime of the cookie is the browser session. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and the cookies remain valid until the set expiration time expires.
    • cookies stored on the hard disk can be shared among different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them. For IE, a window that is opened by pressing CTRL-N (or from the File menu) on an open window can be shared with the original window, while the other way of opening the IE process does not share the memory cookie of the opened window; for Mozilla Firefox0.8, all processes and tabs can share the same cookie. In general, a window opened with JavaScript's will share the memory cookie with the original window. The browser's approach to cookie-only recognition of session cookies is often a major problem for Web application developers who use the sessions mechanism.
//添加cookiesetcookie("name","zxf",time()+3600);//数组 /$arr = array(1,2,3);  $arr_str = serialize($arr);  setcookie("a",$arr_str,time()+3600);  //获取cookie  var_dump($_COOKIE); //更新cookie setcookie("name","aaa",time()+3600); //删除cookie setcookie("name","",time()-20);
Understanding the session mechanism
    • The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.
    • When a program needs to create a session for a client's request, the server first checks to see if a session ID is included in the client's request-called the session ID. If it contains a session The ID indicates that the session was previously created for this client, and the server retrieves the session as session ID (if it is not retrieved, a new one may be created) if the client request does not include the session ID. Creates a session for this client and generates a session Id,session ID value associated with this session should be a string that is neither duplicated nor easily found to be patterned, and this session ID will be returned to the client in this response , the colleague returned to the client will have the Set-cookie parameter on the response header message, which is saved by default with a cookie. If the client does not disable cookies, the way in which the session ID is saved can be a cookie, so that the browser can automatically follow the rules to the server in the same session during the interactive process. If the browser prohibits cookies, there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned.

      Session Storage Issues
    • By default, the SESSION set in php.ini is saved in files (Session.save_handler = files), and file means to save the sesion to a temporary file, if we want to save it in a different way (for example, with a database), You need to set the item to user.
    • Either save the session to a relational database or a non-relational database

Survival time of Session
    • In php.ini, modify the session.gc_maxlifetime=1440//default time
    • The Session also provides a function session_set_cookie_params (); To set the lifetime of the Session, the function must be called before the session_start () function call:

Session automatic expiration Recovery mechanism
    • PHP determines whether to start a GC (garbage) based on the value of the global variable Session.gc_probability/session.gc_divisor (which can also be modified by the php.ini or Ini_set () function). Collector). By default, session.gc_probability =1,session.gc_divisor = 100, which means that there is a 1% possibility to start the GC.

    • The GC's job is to scan all session information, subtract the last modification time (modifieddate) of the session with the current time, and compare it with the Session.gc_maxlifetime parameter if the lifetime has exceeded GC_ Maxlifetime, delete the session.

Gc_maxlifetime Invalid condition
    • By default, session information is saved in the temporary file directory of the system as a text file. Under Linux, this path is typically \tmp, which is typically C:\Windows\Temp under Windows. When there are multiple PHP applications on the server, they will keep their session files in the same directory. Similarly, these PHP applications will launch the GC at a certain probability, scanning all session files.

    • The problem is that when the GC is working, it does not differentiate between sessions at different sites. For example, site A's gc_maxlifetime is set to 2 hours, and Site B's gc_maxlifetime is set to the default of 24 minutes. When the GC of Site B starts, it scans the common temporary files directory and removes all session files that are more than 24 minutes, regardless of whether they come from site A or B. In this way, site A's gc_maxlifetime setting is no more than a dummy.

    • Finding the problem is a simple solution. Modify the Session.save_path parameter, or use the Session_save_path () function to point the directory where the session is saved to a dedicated directory, and the Gc_maxlifetime parameter is working properly.

Gc_maxlifetime outdated not immediately deleted
    • can only guarantee the minimum time for the session to survive, can not be saved after this time, the session information will be deleted immediately. Because the GC is started by chance and may not be started for a long period of time, a large number of sessions will still be valid after more than Gc_maxlifetime. One way to solve this problem is to increase the odds of session.gc_probability/session.gc_divisor, and if you mention 100%, it will solve the problem completely, but it will obviously have a serious impact on performance. Another way is to judge the current session's lifetime in code and empty the current session if the gc_maxlifetime is exceeded.
When cookies are disabled by the browser, the session uses
    • The client (browser) has disabled the cookie, then the server side will not receive the session ID, at this time need to display the pass session ID. Two methods: Pass the session ID manually through the URL, and hide the form pass session ID.
    • You can set the php.ini
      Session.use_trans_sid=1, which means that when the client browser prohibits cookies, the links on the page are passed SessionID based on the URL. But a lot of people just set this one option and didn't get the effect
      There are two options in the php.ini file
      Session.use_cookies indicates whether to start a session based on cookies
      Session.use_only_cookies indicates whether to only open the session mode based on the cookie
    • Therefore, if you want to use cookies in a cookie-based manner when the browser opens the cookie, the following settings will be used when the cookie is not turned on (the most common way, recommended)
      In the php.ini file
      Or in a PHP program.
      Ini_set ("Session.use_trans_sid", "1″");
      Ini_set ("Session.use_only_cookies", 0);
      Ini_set ("Session.use_cookies", 1);

    • Accept the URL in SessionID; (Borrow the session_id () function to get/set the current session ID.)

      session_id($_REQUEST[‘session_id‘]);session_start();  //session_id()在前print_r($_SESSION);
Session Cookies and Persistentcookie
    • Session cookie for a session, the end of Sessioncookie is gone, and Persistentcookie is just a piece of text (usually encrypted) that exists on the client's hard disk. and may be subject to cookie spoofing and cross-site scripting attacks against cookies, which are not as secure as session cookies.
    • Usually Sessioncookie can not be used across windows, when you open a new browser window into the same page, the system will give you a new SessionID, so that the purpose of our information sharing is not reached, At this point we can save the SessionID in the Persistentcookie, and then read it in a new window, you can get the previous window SessionID, so through the session The combination of cookies and Persistentcookie allows us to implement a cross-window session tracking (conversation tracking).

Ref: 16922815

PHP--->cookie and session

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: 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.