The use and disadvantage of cookies in JS

Source: Internet
Author: User
Tags setcookie

   What is Cookies

Cookies mean "Cookie", which is a mechanism developed by the Netscape community, which is proposed by the group . Cookies are now standard and all major browsers such as IE, Netscape, Firefox, and opera support cookies.

Because HTTP is a stateless protocol, the server does not know the identity of the client from the network connection. What do we do? give the client a pass, one per person, who must bring their own pass for whoever accesses it. This allows the server to confirm the identity of the client from the pass. That's how cookies work .

A cookie is actually a small piece of text information. The client requests the server and, if the server needs to log the user state, uses response to issue a cookie to the client browser. The client browser will save the cookie. When the browser requests the site again, the browser submits the requested URL along with the cookie to the server. The server checks the cookie to identify the user state. The server can also modify the contents of the cookie as needed.

Cookies mechanism

In the program, session tracking is a very important thing. Theoretically, all request actions for one user should belong to the same session , and all request actions for another user should belong to another session, and they should not be confused. For example, any item that user a buys in a supermarket should be placed in A's shopping cart, regardless of when user a buys it, it belongs to the same session and cannot be placed in User B or User C's shopping cart, which is not part of the same session.

The Web application transmits data using the HTTP protocol. HTTP the protocol is a stateless protocol. Once the data has been exchanged, the client-to-server connection is closed, and exchanging the data again requires establishing a new connection. This means that the server is unable to track the session from the connection . That is, user a purchases a product into the shopping cart, and when the product is re-purchased, the server is unable to determine whether the purchase is a session of user A or User B. To track this session, you must introduce a mechanism.

Cookies are such a mechanism. It can compensate for the lack of HTTP protocol stateless. Before the session, basically all websites use cookies to track conversations.

JS Set Cookies:

Suppose you want to save the value of the variable username ("Jack") in the a page to the cookie, the key value is name, then the corresponding JS code is:

Document.cookie= "Name=" +username;

You cannot use a semicolon (;), a comma (,), an equal sign (=), and a space in the name or value of a cookie. It is easy to do this in the name of the cookie, but the value to be saved is indeterminate. How do you store these values? The method is encoded with the escape () function, which can use hexadecimal notation for some special symbols, such as spaces that will be encoded as "20%", which can be stored in cookie values, and the use of this scheme can also avoid the occurrence of Chinese garbled characters.

Document.cookie= "str=" +escape ("I love Ajax");

Document.cookie= "Str=i%20love%20ajax";

When the Escape () code is used, unescape () is used to decode the value after it is removed to obtain the original cookie value.

JS Read Cookies:

Assume that the content stored in the cookie is: name=jack;password=123

The JS code that gets the value of the variable username in the B page is as follows:

var username=document.cookie.split (";") [0].split ("=") [1];

JS Operation Cookies Method!

Write cookies

function Setcookie (name,value)

{

var days = 30;

var exp = new Date ();

Exp.settime (Exp.gettime () + days*24*60*60*1000);

Document.cookie = name + "=" + Escape (value) + "; expires=" + exp.togmtstring ();

}

Read Cookies

function GetCookie (name)

{

var arr,reg=new RegExp ("(^|)" +name+ "= ([^;] *)(;|$)");

if (Arr=document.cookie.match (REG))

Return unescape (arr[2]);

Else

return null;

}

Delete Cookies

function Delcookie (name)

{

var exp = new Date ();

Exp.settime (Exp.gettime ()-1);

var cval=getcookie (name);

if (cval!=null)

document.cookie= name + "=" +cval+ "; expires=" +exp.togmtstring ();

}

Using the example

Setcookie ("name", "Hayden");

Alert (GetCookie ("name"));

If you need to set a custom expiration time

Then replace the above Setcookie function with the following two functions OK;

Program code

function Setcookie (name,value,time)

{

var strsec = getsec (time);

var exp = new Date ();

Exp.settime (Exp.gettime () + strsec*1);

Document.cookie = name + "=" + Escape (value) + "; expires=" + exp.togmtstring ();

}

function Getsec (str)

{

alert (str);

var str1=str.substring (1,str.length) * *;

var str2=str.substring (0,1);

if (str2== "s")

{

return str1*1000;

}

else if (str2== "H")

{

return str1*60*60*1000;

}

else if (str2== "D")

{

return str1*24*60*60*1000;

}

}

This is an example of using a set expiration time:

S20 is represented for 20 seconds

H refers to the hour, such as 12 hours: H12

D is the number of days, 30 days: D30

Setcookie ("name", "Hayden", "S20");

Cookie Disadvantage

Although cookies provide the convenience of persisting client data, they share the burden of server storage, but there are many limitations.

First: Generate up to 20 cookies per specific domain name

1.ie6 or lower version up to 20 cookies

2.ie7 and later versions can have 50 cookies at the end.

3.Firefox Maximum of 50 cookies

4.chrome and Safari do not make hard restrictions

IE and opera will clean up the least recently used Cookie,firefox will randomly clean up cookies.

The maximum number of cookies is approximately 4096 bytes, and for compatibility, it is generally not more than 4095 bytes.

IE provides a kind of storage that can persist user data, called Uerdata, and support from IE5.0. Each data is up to 128K, up to 1M under each domain name. This persisted data is placed in the cache and will persist if the cache is not cleaned up.

Benefits: Very high scalability and availability

1. Control the size of the session object saved in the cookie through good programming.

2. Reduce the likelihood of cookies being cracked through encryption and secure transfer technology (SSL).

3. Only non-sensitive data is stored in a cookie, and there is no significant loss even if it is stolen.

4. Control the lifetime of the cookie so that it does not last forever. A thief is likely to get an expired cookie.

Disadvantages:

1. Limits on the number and length of ' cookies '. There can be up to 20 cookies per domain, each cookie cannot exceed 4KB in length, or it will be truncated.

2. Security issues. If a cookie is intercepted, the person can get all the session information. Even if encryption is not a problem, because the interceptor does not need to know the meaning of the cookie, he can only forward the cookie as it is to achieve the purpose.

3. Some states cannot be saved on the client. For example, to prevent a duplicate submission of a form, we need to save a counter on the server side. If we keep this counter on the client, it doesn't make any difference.

The use and disadvantage of cookies in JS

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.