To fully understand the Cookie

Source: Internet
Author: User
Tags cookie names
Cookie is a variable stored on the visitor's computer. Each time a computer requests a page through a browser

I have been engaged in web development for some days. I can hardly understand what cookies are, but I actually need to search for them (You know) on my own, and the results are despised... so I wrote a blog post as my study notes. The benefits of my blog are shown here.

What is Cookie?

"Cookie is a variable stored on the visitor's computer. This cookie is sent every time a computer requests a page through a browser. You can use JavaScript to create and retrieve cookie values ." -W3school

A cookie is a file created on a visited website. It is used to store browsing information, such as personal information.

From the JavaScript perspective, cookies are strings. This information is stored in the client computer and used to transmit information between the client computer and the server.

In JavaScript, you can use document. cookie to read or set this information. Because cookies are mostly used for communication between the client and the server, in addition to JavaScript, the server language (such as PHP) can also access cookies.

Basic Cookie knowledge
  • A cookie has a size limit. Each cookie cannot store more than 4 kb of data. If the cookie string length exceeds 4 kb, this attribute returns an empty string.
  • Because cookies are stored in the client computer as files, it is convenient to view and modify cookies. This is why Cookies cannot store important information.
  • The format of each cookie is as follows: = <值> ; Names and values must both be valid identifiers.
  • Cookie is valid. By default, the lifecycle of a cookie ends when the browser is closed. If you want to use a cookie after it is disabled by the browser, you must set a validity period for the cookie, that is, the expiration date of the cookie.
  • Alert (typeof document. cookie) returns a string. I thought it was an array and made a joke...
  • Cookie has the concept of domain and path. Domain is the concept of domain. Because browsers are secure environments, different domains cannot access each other's cookies (of course, cross-origin cookie access can be achieved through special settings ). PATH is the concept of routing. A cookie created by a webpage can only be accessed by all webpages in the same directory or subdirectory as the webpage, it cannot be accessed by web pages in other directories (this sentence is a bit difficult, so I will understand it after looking at an example later ).
  • In fact, the method for creating a cookie is similar to that for defining a variable. Both cookie names and cookie values are required. Multiple cookies can be created for the same website, and multiple cookies can be stored in the same cookie file.
Cookie FAQs

There are two types of cookies:

  • The cookie set for the current website you are browsing
  • Third-party cookies from other domain sources such as advertisements or Images embedded on webpages (websites can use these cookies to track your usage information)

As mentioned in the basic knowledge, the cookie lifecycle can be roughly divided into two statuses:

  • Temporary cookies. During the current use process, the website will store some of your personal information, which will be deleted from the computer after the browser is closed.
  • Set the cookie with the expiration time. Even if the browser is closed, the information industry will still be in the computer. Such as the logon name and password, you do not need to log on to a specific site each time. This cookie can be retained on a computer for several days, months, or even years.

There are two methods to clear cookies:

  • Clear cookies using browser Tools (with third-party tools, the browser also has this function)
  • Clear the cookie by setting the cookie Validity Period
  • Note: deleting a cookie may cause some webpages to fail to run normally.

The browser can accept and reject access cookies through settings. For functional and performance reasons, we recommend that you reduce the number of cookies and use small cookies whenever possible.

For a page on a local disk, the chrome console cannot use JavaScript to read and write cookies. The solution is to change the browser to pai_^.

Basic Cookie usage

1. Simple access operations

When using JavaScript to access cookies, you must use the cookie attribute of the Document Object. A line of code describes how to create and modify a cookie:

document.cookie  = 'username=Darren'

In the above Code, 'username' indicates the cookie name, And 'darren' indicates the value corresponding to this name. If the cookie name does not exist, a new cookie is created. If the cookie name exists, the corresponding value is modified. If you want to create a cookie multiple times, repeat this method.

2. cookie reading

To precisely read cookies, it is actually very easy to perform operations on strings. Copy this code from w3school for analysis:

Function getCookie (c_name) {if (document. cookie. length> 0) {// first query whether the cookie is null. If it is null, return "" c_start = document. cookie. indexOf (c_name + "=") // use the indexOf () of the String object to check whether the cookie exists. if it does not exist, it is-1 if (c_start! =-1) {c_start = c_start + c_name.length + 1 // The last + 1 actually represents the "=" number, so that the start position of the cookie value is c_end = document. cookie. indexOf (";", c_start) // In fact, when I first saw the second indexOf () parameter, I suddenly felt a little dizzy. Later I remembered that it represented the specified start index position... this is to get the end position of the value. Because you need to consider whether it is the last item, you can determine whether the if (c_end =-1) c_end = document by using the ";" sign. cookie. length return unescape (document. cookie. substring (c_start, c_end) // obtain the value through substring. If you want to know unescape (), you must first know what escape () is. It is a very important foundation. If you want to know it, you can search for it, at the end of the article, we will also explain the cookie encoding details} return ""}

Of course there are still many methods to read cookies, such as arrays and regular expressions. I will not elaborate on them here.

3. Set the cookie Validity Period

In this article, the life cycle of the cookie, that is, the validity period and expiration period, that is, the time when the cookie exists. By default, cookies are automatically cleared when the browser is closed, but we can use expires to set the cookie validity period. Syntax:

document.cookie = "name=value;expires=date"

The date value in the above Code is a date string in GMT (Greenwich Mean Time) format. The generation method is as follows:

var _date = new Date();_date.setDate(_date.getDate()+30);_date.toGMTString();

The above three lines of code are divided into several steps:

  • Generate a Date instance using new to get the current time;
  • The getDate () method is used to obtain a day in the current local month. Then, 30 is added, which means that the cookie can be saved locally for 30 days;
  • The setDate () method is used to set the time;
  • Finally, the toGMTString () method is used to convert the Date object to a string and return the result.

The following complete function is used to describe what we need to pay attention to when creating cookies-copied from w3school. Create a function to store information in cookies:

Function setCookie (c_name, value, expiredays) {var exdate = new Date (); exdate. setDate (exdate. getDate () + expiredays); document. cookie = c_name + "=" + escape (value) + (expiredays = null )? "": "; Expires =" + exdate. toGMTString ();} // usage: setCookie ('username', 'darren', 30)

Now, we use this function to set the cookie validity period based on the number of days. If you want to set it in another unit (such as hour), you can change the third line of code:

exdate.setHours(exdate.getHours() + expiredays);

In this way, the cookie validity period is calculated on an hourly basis. I have mentioned two methods to clear a cookie. Now I want to disable the cookie by setting the validity period to an expiration time. Now that you have a method to set the validity period, you can set the failure period. Next we will continue to talk about cookie topics.

Cookie advanced

1. cookie Path Concept

I have mentioned in the basic knowledge that cookie has the concept of domain and path. Now I will introduce the role of path in cookie. Generally, a cookie is created because the user accesses the page. However, the cookie is not accessible only on the page where the cookie is created.

By default, only webpages in the same directory or subdirectory as the page for cookie creation can be accessed. This is because of security considerations, not all pages can access the cookies created on other pages at will. For example:

Create a cookie on the "http://www.nowamagic.net/Gonn/" page, then the page under the path "/Darren_code/", such as: "http://www.nowamagic.net/Gonn/archive/2011/11/07/Cookie.html", will be able to get the cookie information by default.

By default, the cookie cannot be accessed by "http://www.nowamagic.net" or "http://www.nowamagic.net/xxxx/" (it's useless to look at it, and the truth goes through ^_^ ).

So how to make this cookie accessible to other directories or parent directories can be achieved by setting the cookie Path. Example:

document.cookie = "name=value;path=path"document.cookie = "name=value;expires=date;path=path"

The path in the red font is the cookie path. The most common example is to keep the cookie in the directory. In this way, no matter which sub-page the cookie is created, all the pages can be accessed:

document.cookie = "name=Darren;path=/"

2. cookie domain concept

The path can solve the problem of cookie access in the same domain. Let's talk about the problem of cookie access between the same domain. Syntax:

document.cookie = "name=value;path=path;domain=domain"

The red domain is the set cookie domain value.

For example, "www.qq.com" and "sports.qq.com" share an associated domain name "qq.com". If we want the cookie under "sports.qq.com" to be accessed by "www.qq.com, we need to use the domain attribute of the cookie and set the path attribute "/". Example:

document.cookie = "username=Darren;path=/;domain=qq.com"

Note: It must be the access between the same domain. The domain value cannot be set as a domain name of a non-primary domain.

3. cookie Security

Generally, cookie information is transmitted through an HTTP connection. This transmission method is easy to view, so the information stored in cookies is easily stolen. If the content transmitted in cookies is important, encrypted data transmission is required.

Therefore, the name of the cookie attribute is "secure" and the default value is null. If the attribute of a cookie is secure, data is transmitted between the cookie and the server over HTTPS or other security protocols. Syntax:

document.cookie = "username=Darren;secure"

Setting the cookie as secure only ensures that the data transmission process between the cookie and the server is encrypted, while the cookie files stored locally are not encrypted. If you want to encrypt the local cookie, you must encrypt the data yourself.

Note: even if the secure attribute is set, it does not mean that others cannot see the cookie information stored locally on your machine. In the end, do not put the important information in the cookie.

4. cookie encoding details

I originally wanted to introduce the knowledge of cookie encoding in the FAQ section, because if I don't know about it, the encoding problem is indeed a pitfall, so I 'd like to explain it in detail.

When entering cookie information, it cannot contain spaces, semicolons, commas, and other special characters. In general, the storage of cookie information is not encoded. Therefore, before setting cookie information, you must use the escape () function to encode the cookie value information and use the unescape () function to convert the value when obtaining the cookie value. For example, when setting a cookie:

document.cookie = name + "="+ escape (value)

Let's take a look at the getCookie () mentioned in the basic usage:

return unescape(document.cookie.substring(c_start,c_end))

In this way, you do not have to worry about cookie Information errors due to special characters in the cookie value.

Summary

The importance of the foundation is becoming more and more important in the work. There are many technical details that need to be understood or not understood much. In order to improve this situation, I plan to understand the details of the knowledge from the point to the point, and then write a blog to deepen my impression and share it with more friends who need it.

Address of this article: http://www.nowamagic.net/librarys/veda/detail/801,welcome.

Related Article

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.