Client data is stored ---- Cookie From "Elevation 3"

Foreword

This part describes the study are summarized Cookie technology, but I think the best would be a logical and comparison Web Storage technologies together, so follow-up will then sum up an article on WEB storage sister summed up, so stay tuned.

First come first section summarizes : Cookie a local data store, present in the response server and a Set-Cookie header browser interaction and Cookie request header, limited by the number of Cookie, Cookie single size, performance, security restrictions single domain . There is a sub Cookie technology to ease the limit on the number of single domain name Cookie, Cookie has a set of tools on sub-functions can be used.

HTTP Cookie Profile

The best user information stored on the client, which the client data is stored forth requirements. The first solution is to Cookie. HTTP Cookie, usually directly called the cookie, the client was originally used to store session information. The standard requires server sends Set-Cookie HTTP header as part of any HTTP response containing the session information.

A typical response header:

HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: name=value
Other-header: other-header-value

The HTTP response sets a cookie to name the name to value as the value of the name and the value at the time of transmission must be URL-encoded. Browser stores this information session, and after that, will be sent back to the server by adding a Cookie header information for each request:

GET /index.html HTTP/1.1
Cookie: name=value
Other-header: other-header-value

Cookie's visit, the number and size limits

cookie in nature is bound to a particular domain name. When the set a cookie, created to give its domain sends a request, it will include the cookie. This restriction ensures that the recipient of the information stored in the cookie can only make approval of access, and can not be accessed by other domains.

Since the cookie is present on the client computer, but also added some restrictions to ensure the cookie will not be used maliciously, but will not take up too much disk space. The total number of cookie per domain is limited, but varies between browsers:
1) IE6 and earlier limit of up to 20 per domain cookie.
2) IE7 and later versions of each domain name up to 50. IE7 was originally supported a maximum 20 per domain name cookie, after being updated by a Microsoft patch.
3) Firefox limit up to 50 per domain cookie.
4) Opera limit up to 30 per domain cookie.
5) Safari and Chrome is not mandatory for cookie limit per domain.

After more than a single domain name restrictions still have to set a cookie, browser cookie will clear previously set. IE and Opera will delete the least recently used (LRU, Least Recently Used) cookie, make room for the new cookie set. Firefox looks like random which decided to clear the cookie, it is important to consider the cookie limit in order to avoid unpredictable consequences.

Browser, there is a limit to the size of the cookie. Most browsers have about 4096B (plus or minus 1) length limit. For optimal browser compatibility, it is preferable to limit the length of the entire cookie 4095B (including 4095) within. Affect all size limitations next domain cookie, rather than each individual cookie limits. If you try to create a cookie exceeds the maximum size limit, then the cookie will be quietly discarded.

cookie composition

1) Name: determine a unique name of the cookie. cookie names are case-insensitive. The cookie name must be URL-encoded.
2) Value: string value is stored in a cookie. The value must be URL encoded.
3) Domain: cookie is valid for which domain. All requests are sent to the domain that contains cookie information.
4) path: the path specified for that domain, cookie should be sent to the server.
5) expiration time: Indicates the timestamp (ie, when it should stop sending the cookie to the server) cookie when it should be deleted. By default, all about to delete the cookie at the end of the browser session; but you can also set up their own time to delete. This value is a date in GMT (Wdy, DD-Mon-YYYY HH: MM: SS GMT), is used to specify the exact time the cookie should be deleted. Therefore, cookie may still stored on the user's machine after the browser is closed. If you set the expiration date of a previous time, the cookie will be deleted immediately.
6) Safety signs: After you specify, cookie sent to the server only when using an SSL connection. E.g., cookie information can only be sent to https://www.wrox.com , and http://www.wrox.com request can not be transmitted cookie.

Each piece of information are Set-Cookie header as part of spaces separated by a semicolon each segment. secure logo is the only non-cookie name value portion of the children directly contains a secure word. Particular attention, domain, path, expiration time and logo are secure server to instruct the browser (is sent back from the server response) to specify when it should be sending cookie. These parameters will not be sent to the server as part of the cookie information, only the name value will only be sent to the server for the child.

Set the cookie format, and the format used in the Set-Cookie header as follows:
name = value; Expires = EXPIRATION_TIME; path = domain_path;
Domain = DOMAIN_NAME; Secure

Create, delete and visit Cookie utility functions

Because JavaScript to read and write cookie is not very intuitive, often you need to write some functions to simplify the cookie function. There are three basic cookie operations: read, write, and delete. Create a cookie utility functions:

    var CookieUtil = {
    get: function (name) {
    var cookieName = encodeURIComponent(name) + '=',
    cookieStart = document.cookie.indexOf(cookieName),
    cookieValue = null;
    if (cookieStart > - 1) {
      var cookieEnd = document.cookie.indexOf(';', cookieStart);
      if (cookieEnd == - 1) {
        cookieEnd = document.cookie.length;
      }
      cookieValue = decodeURIComponent(document.cookie.substring(cookieStart
      + cookieName.length, cookieEnd));
    }
    return cookieValue;
  },
  set: function (name, value, expires, path, domain, secure) {
    var cookieText = encodeURIComponent(name) + '=' +
    encodeURIComponent(value);
    if (expires instanceof Date) {
      cookieText += '; expires=' + expires.toGMTString();
    }
    if (path) {
      cookieText += '; path=' + path;
    }
    if (domain) {
      cookieText += '; domain=' + domain;
    }
    if (secure) { //secure在这里是布尔值
      cookieText += '; secure';
    }
    document.cookie = cookieText;
  },
  unset: function (name, path, domain, secure) {
    this.set(name, '', new Date(0), path, domain, secure);
  }

};

CookieUtil.get () method to get the appropriate value based on the name of the cookie. It will find the location of cookie name with an equals sign in the document.cookie string. If found, then use the indexOf () to find the first semicolon after the position (end position represents the cookie). If the semicolon is not found, then the cookie string is the last one, the value of the rest of the string is the cookie. This value is used decodeURIComponent () decodes and finally returns. If no cookie, null is returned.
CookieUtil.set () method to set a cookie on the page, receives the following parameters: the name of the cookie and the cookie value, optionally for a specific cookie should be removed when the Date object, cookie optional URL path , optional fields, and an optional flag indicating whether you want to add secure Boolean value. Parameters are listed according to their frequency of use, only the first two are required. In this method, the value of the name and use encodeURIComponent () has been URL encoded, and check other options. If the expires parameter is a Date object, then use the Date object toGMTString () method properly formatted Date objects, and added to the option expires. Other parts of the method is configured cookie string and sets it into the document.cookie.
There is no direct method of cookie deletion. Therefore, the need to use the same path, domain, and security options set a cookie again, and set the expiration time to time in the past. CookieUtil.unset ()Ways to handle this kind of thing. It receives four parameters: the name of the cookie you want to delete, optional path parameter, an optional domain parameters and optional security parameters. These parameters plus an empty string and set the time to failure (Date object is initialized to the 0ms) January 1, 1970, passed CookieUtil.set (). This ensures that deleted cookie.

FireBug test results

FireBug corresponds to which page, cookie settings are stored in the domain corresponding to that page. Open local apache server / localhost / alien / page, in which the open firebug.
Test Example 1:

    CookieUtil.set("name", "Nicholas");
    CookieUtil.set("book", "Professional JavaScript");
    //读取 cookie 的值
    console.log(CookieUtil.get("name")); //"Nicholas"
    console.log(CookieUtil.get("book")); //"Professional JavaScript"

image description

Test Example 2 delete the cookie:
CookieUtil.unset ( "name");
CookieUtil.unset ( "Book");
this time FireBug does not show any Cookie.

Test Example 3 Open the local server localhost home page, set the security of cookie.
CookieUtil.set ( "name", "Nicholas", null, null, null, to true);
the console.log (CookieUtil.get ( "name"));
when the secure set to true, the front of the missing parameters are defined as null. This is because the parameters in the order corresponding to the JavaScript. Test results: security items appear "safe."
image description

子Cookie

Sub Cookie purpose is to break quantity Cookie in single domain, i.e. in a Cookie storing a plurality of name-value pairs, the common format:
name = NAME1 = VALUE1 & NAME2 = value2 & NAME3 = value3 & NAME4 = value4 & NAME5 = Value5

Cookie settings on the sub, get, and delete the following utility functions:

var SubCookieUtil = {
  get: function (name, subName) {
    var subCookies = this.getAll(name);
    if (subCookies) {
      return subCookies[subName];
    } else {
      return null;
    }
  },
  getAll: function (name) {
    var cookieName = encodeURIComponent(name) + '=',
    cookieStart = document.cookie.indexOf(cookieName),
    cookieValue = null,
    cookieEnd,
    subCookies,
    i,
    parts,
    result = {
    };
    if (cookieStart > - 1) {
      cookieEnd = document.cookie.indexOf(';', cookieStart);
      if (cookieEnd == - 1) {
        cookieEnd = document.cookie.length;
      }
      cookieValue = document.cookie.substring(cookieStart +
      cookieName.length, cookieEnd);
      if (cookieValue.length > 0) {
        subCookies = cookieValue.split('&');
        for (i = 0, len = subCookies.length; i < len; i++) {
          parts = subCookies[i].split('=');
          result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
        }
        return result;
      }
    }
    return null;
  },
  set: function (name, subName, value, expires, path, domain, secure) {
    var subcookies = this.getAll(name) || {
    };
    subcookies[subName] = value;
    this.setAll(name, subcookies, expires, path, domain, secure);
  },
  setAll: function (name, subcookies, expires, path, domain, secure) {
    var cookieText = encodeURIComponent(name) + '=',
    subcookieParts = new Array(),
    subName;
    for (subName in subcookies) {
      //由于采用push方法,新的子Cookie被延续到原来的Cookie中
      if (subName.length > 0 && subcookies.hasOwnProperty(subName)) {
        subcookieParts.push(encodeURIComponent(subName) + '=' +
        encodeURIComponent(subcookies[subName]));
      }
    }
    if (subcookieParts.length > 0) {
      cookieText += subcookieParts.join('&');
      if (expires instanceof Date) {
        cookieText += '; expires=' + expires.toGMTString();
      }
      if (path) {
        cookieText += '; path=' + path;
      }
      if (domain) {
        cookieText += '; domain=' + domain;
      }
      if (secure) {
        cookieText += '; secure';
      }
    } else {
      cookieText += '; expires=' + (new Date(0)).toGMTString();
    }
    document.cookie = cookieText;
  },
  unset: function (name, subName, path, domain, secure) {
    var subcookies = this.getAll(name);
    if (subcookies) {
      delete subcookies[subName];
      this.setAll(name, subcookies, null, path, domain, secure);
    }
  },
  unsetAll: function (name, path, domain, secure) {
    this.setAll(name, null, new Date(0), path, domain, secure);
  }
};

The following is a parsing of the above methods:
a method of obtaining sub cookie has two: GET () and getAll () . Wherein the get () Gets the value of a single sub cookie, the getAll () Gets all sub cookie and returns them into an object, the attribute name of the child object's cookie, the cookie corresponding to a value corresponding to the value of the sub. get () method accepts two parameters: the name of the cookie's name and child cookie. It is actually calling getAll () Gets all the child cookie, then return only required that one (if the cookie does not exist then return null).

SubCookieUtil.getAll () method and CookieUtil.get () in a manner very similar to parsing cookie value. The difference is that the value of the cookie is not decoded immediately, but the first character in accordance with the sub-& cookie carved out in an array, each sub-division cookie again based on the equal sign, so the first part is the name of the cookie in parts sub-array, the latter part is the value of the sub cookie. The two items have to use decodeURIComponent () to decode, then the result object placed in the last as the return value. If the cookie does not exist, null is returned.

set () method receives seven parameters: the cookie name, sub-name of the cookie, the sub cookie value, optional cookie Date object date or time failure, optionally cookie path, and an optional cookie domain secure optional Boolean flag . All optional parameters are applied to the cookie itself, not the child cookie. In the same cookie for storing a plurality of sub cookie, path, and the secure domain must match flag; may be provided at any time while a single child writes a cookie expiration date for the entire cookie. In this method, the first step is to get all the child cookie cookie corresponding to the name specified. Logical OR operator "||" is used when the getAll () will return null subcookies to a new object. Then, set up sub cookie value on subcookies object and pass setAll ().

SetAll () method receives six parameters: the name of cookie, the cookie contains the object and all child and set () as in the four optional parameters. This method uses the for-in loops through the second parameter attributes. In order to ensure that the data to be saved is indeed used hasOwnProperty () method, to ensure that only instance of the sub-attribute is serialized into a cookie. Because there may be a case attribute name is empty string, so before adding the name of the property to check the result of the object but also the length of the property name. The name of the cookie value each child for children of all stored subcookieParts array, so that you can later use join () method to combine the ampersand.

Ordinary cookie expiration time can be set as a method to delete the last time, but the child cookie can not do that. To delete a cookie child, the child must first get all the cookie contained in a cookie, and then only delete the cookie you want to delete the child, and then save the value then the rest of the sub cookie is a cookie value. unset () method is used to delete a single sub cookie in the cookie without affecting the other; and unsetAll () method is equivalent to CookieUtil.unset (), to delete the entire cookie. And set () and setAll () the same path, domain, and signs must be consistent and secure content cookie contains previously created.

firebug test case

//设置两个 cookie
SubCookieUtil.set("data", "name", "Nicholas");
SubCookieUtil.set("data", "book", "Professional JavaScript");
image description

// set all sub cookie expiration date and
SubCookieUtil.setAll ( "data", {name : "Nicholas", book: "Professional JavaScript"}, new Date ( "January 1, 2018"));
image description

// change the value of the name, and modify the cookie expiration date
SubCookieUtil.set ( "data", "name ", "Michael", new Date ( "February 1, 2010"));
image description

// delete all child Cookie
SubCookieUtil.unsetAll ( 'the Data');

Cookie restrictions

1) limit the number and size of single domain name restrictions: only child Cookie Cookie breaking the limit on the number under a single domain name, but is still limited by the size of the Cookie, so pay attention to the child's size can not make a single Cookie Cookie exceeds the size limit.
2) performance limitations: Because all of the cookie from the browser are sent as a request header, the store large amounts of information can affect the performance of domain-specific request in the cookie. cookie information is greater, the longer the time to complete the server request. Although the browser cookie can be a size limit, but better to store information in a cookie as little as possible in order to avoid affecting performance.
3) security restrictions: cookie data is not stored in a secure environment, any data contained therein can be accessed by others. So do not store personal data such as credit card numbers or addresses and the like in a cookie.
the nature of the cookie and its limitations makes it an ideal and not a lot of information as a means of storage, and so there are other methods.

This article is reproduced in: ape 2048➞ https://www.mk2048.com/blog/blog.php?id=hhjc0ccabjb

Guess you like

Origin www.cnblogs.com/homehtml/p/12594295.html