What is a Cookie
"Cookies are variables that are stored on the computer of the visitor. This cookie is sent whenever the same computer requests a page through the browser. You can use JavaScript to create and retrieve a cookie's value. "-W3school
A cookie is a file created by a visited web site to store browsing information, such as personal information.
From the JavaScript point of view, cookies are some string information. This information is stored on the client computer and is used to pass information between the client computer and the server.
This information can be read or set by Document.cookie in JavaScript. Because cookies are used for communication between the client and the server, the language of the server (such as PHP) can also access cookies in addition to JavaScript.
Cookie Basics
Cookies are limited in size, each cookie holds no more than 4kb of data, and if the length of the cookie string exceeds 4KB, the property returns an empty string.
Since cookies are ultimately stored as files on the client computer, it is convenient to view and modify cookies, which is why it is often said that cookies do not store important information.
The format of each cookie is the same: <cookie name >=< value >; name and value must be valid identifiers.
Cookies are valid for validity. By default, the life cycle of a cookie ends when the browser closes. If you want cookies to be available after the browser is turned off, you must set the expiration date for the cookie, which is the expiration of the cookie.
Alert (typeof Document.cookie) result is string, once I thought is array, also make joke ... 囧
Cookies have the concept of domain and path. Domains are the concept of domain, because browsers are security-aware environments, so different domains cannot access cookies between each other (and, of course, through a special set of cookies that are reachable across domains). The path is the concept of routing, a Web page created a cookie can only be with the Web page in the same directory or subdirectory access to all Web pages, and can not be the other directory access to the Web page (this sentence is a bit around, a look at an example is good to understand).
In fact, the way you create cookies is similar to the way you define variables, and you need to use cookie names and cookie values. The same Web site can create multiple cookies, and multiple cookies can be stored in the same cookie file.
Cookie FAQ
There are two types of cookies:
Cookies that you have browsed the current site itself set
Third-party cookies from other domain sources such as ads or pictures embedded on a Web page (Web sites can use these cookies to track your usage information)
The basics have just been about the cookie lifecycle, but cookies can be roughly divided into two states:
Cookies of a temporary nature. The current use of the site will store some of your personal information, when the browser is closed after the information will be removed from the computer
Set the cookie for the expiration time. Even if the browser shuts down, the information industry will still be on the computer. such as the login name and password, so you do not need to log on every time you visit a particular site. This cookie can be kept in a computer for days, months, or years.
There are two ways to clear cookies:
Using browser tools to clear cookies (with Third-party tools, the browser itself has this feature)
To clear cookies by setting the expiration date of a cookie
Note: Deleting cookies can sometimes cause some pages to not function correctly
The browser can be set to accept and deny access to cookies.
For functional and performance reasons, it is recommended that you minimize the number of cookies used and use small cookies as much as possible.
Details about the cookie encoding will be presented separately in the cookie advanced article.
If it is a page on a local disk, the Chrome console is unable to use JavaScript to read and write the cookie, the solution ... Change to a browser ^_^.
Cookie Base Usage
A. Simple access operation
When using JavaScript to access cookies, you must use the cookie property of the Document object; a line of code describes how to create and modify a cookie:
Copy Code code as follows:
Document.cookie = ' Username=darren ';
In the above code ' username ' denotes the cookie name, ' Darren ' indicates the value of the name. Assuming that the cookie name does not exist, create a new cookie, or modify the value of the cookie name if it exists. If you want to create a cookie multiple times, use this method repeatedly.
Two. read operation of Cookies
The exact way to read a cookie is simply to manipulate the string. Copy this code from the W3school to do the analysis:
Copy Code code as follows:
function GetCookie (c_name) {
if (document.cookie.length>0) {///First query whether the cookie is empty, return ""
C_start=document.cookie.indexof (c_name + "=")//through the String object's IndexOf () to check whether the cookie exists, does not exist 1
if (c_start!=-1) {
C_start=c_start + c_name.length+1//finally this +1 actually means "=", so you get the starting position of the cookie value
C_end=document.cookie.indexof (";", C_start)//In fact, I just saw IndexOf () the second parameter when suddenly a bit dizzy, then remembered to indicate the location of the specified start index ... This sentence is to get the end position of the value. Because of the need to consider whether the last one, so through the ";" Whether the number exists to judge
if (c_end==-1) c_end=document.cookie.length
Return unescape (document.cookie.substring (c_start,c_end))//Gets the value through substring (). To understand Unescape () is to know what escape () is to do, are very important basis, want to understand the search can be, at the end of the article will also explain the cookie coding details
}
}
Return ""
}
Of course, there are a number of ways to read cookies, such as arrays, and so on, here is not to elaborate.
Three. Set the expiration date of the cookie
The life cycle of the cookie that often appears in the article is the period of validity and expiration, that is, the existence time of the cookie. By default, cookies are automatically cleared when the browser is closed, but we can set the expiration date of the cookie by expires. The syntax is as follows:
Copy Code code as follows:
Document.cookie = "Name=value;expires=date";
The date-type string in the preceding code, in GMT (GMT) format, is generated as follows:
Copy Code code as follows:
var _date = new Date ();
_date.setdate (_date.getdate () +30);
_date.togmtstring ();
The above three lines of code are broken down into several steps:
Generate a date instance through new to get the current time;
The GetDate () method gets the day of the current local month, plus 30 is what I want the cookie to be stored locally for 30 days;
Then the Setdate () method is used to set the time;
Finally, the date object is converted to a string using the toGMTString () method, and the result is returned
Here's a complete function to illustrate what we need to be aware of in creating cookies-copied from W3school. To create a function that stores information in a cookie:
Copy Code code as follows:
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 ());
}
How to use: Setcookie (' username ', ' Darren ', 30)
Now our function is to set the valid time of the cookie according to the number of days, if you want to set it in other units (such as: hours), then change the third line of code:
Copy Code code as follows:
Exdate.sethours (exdate.gethours () + expiredays);
After this setting, the cookie validity period is in hours.
There are two ways to get rid of cookies in common problems, but now it's time to disable the cookie by setting the expiration date to an expired time. Now that there is a way to set the expiration date, then the method of setting the expiration period invites interested friends to do their own ^_^. Below continue the deeper cookie topic.
Cookie Advanced Article
A. Cookie path concept
In the basics, there is a reference to the notion that a cookie has a domain and a path, now to describe the path's role in the cookie.
Cookies are typically created by the user accessing the page, but not only on the page where the cookie is created.
By default, only pages that are in the same directory or subdirectory as the page in which the cookie was created are accessible because of security considerations that do not allow all pages to freely access cookies created by other pages. As an example:
To create a cookie on the "http://www.jb51.net/Darren_code/" page, the page under the "/darren_code/" path is like: "Http://www.jb51.net/Darren_code /archive/2011/11/07/cookie.html "This page will be able to get Cookie information by default.
By default, "Http://www.jb51.net" or "http://www.jb51.net/xxxx/" can not access this cookie (the light is useless, practice truth ^_^).
So how to get this cookie to be accessed by other directory or parent directory Access class, by setting the path of the cookie can be implemented. Examples are as follows:
Copy Code code as follows:
Document.cookie = "Name=value;path=path"
Document.cookie = "Name=value;expires=date;path=path"
The red type path is the path to the cookie, and the most common example is to have the cookie in the directory, so that no matter which child page created the cookie, all pages can be accessed:
Copy Code code as follows:
Document.cookie = "name=darren;path=/";
Two. cookie Domain concept
The path solves the problem of accessing cookies under the same domain, and we go on to say that cookies implement the problem of accessing the same domain. The syntax is as follows:
Copy Code code as follows:
Document.cookie = "Name=value;path=path;domain=domain";
The red domain is the value of the cookie field set.
For example, "www.qq.com" and "sports.qq.com" common an associated domain name "qq.com", if we want to "sports.qq.com" cookies under "www.qq.com" access, we need to use cookies Domain attribute, and you need to set the Path property to "/". Cases:
Copy Code code as follows:
Document.cookie = "username=darren;path=/;d omain=qq.com";
Note: A certain is the access between the same domain, you can not set the value of domain to the domain name of the non-primary domain.
Three. Cookie Security
Cookie information is usually used to pass data using an HTTP connection, which can be easily viewed, so cookies store information that is easily stolen. If the content passed in the cookie is more important, then the encrypted data transfer is required.
So the name of this property for the cookie is "secure," and the default value is null. If the property of a cookie is secure, it communicates data between the server via HTTPS or another security protocol. The syntax is as follows:
Copy Code code as follows:
Document.cookie = "Username=darren;secure"
Setting the cookie to secure only guarantees that the data transfer process between the cookie and the server is encrypted, while the locally stored cookie file is not encrypted. If you want to encrypt the local cookie, you have to encrypt the data yourself.
Note: Even if the secure attribute is set, it does not mean that others cannot see the cookie information that is stored locally on your machine, so in the final analysis, don't put the important information in cookies.
Four. Cookie coding details
Originally wanted to introduce the cookie code knowledge in the FAQ section, because if you don't know the coding problem is really a pit, so say it in detail.
When you enter cookie information, you cannot include spaces, semicolons, commas, and other special symbols, and in general, the storage of cookie information is in a way that is not encoded. So, before setting cookie information, use the escape () function to encode the cookie value information, and then use the unescape () function to convert the value back when the cookie is worth the time. When setting cookies:
Copy Code code as follows:
Document.cookie = name + "=" + escape (value);
Take a look at the phrase in GetCookie () mentioned in the basic usage:
Copy Code code as follows:
Return unescape (document.cookie.substring (c_start,c_end));
This doesn't have to worry because there is a special symbol in the cookie value that causes the cookie information to go wrong.
Personal code
Copy Code code as follows:
/* Set cookie*/
function Setcookie (c_name, value, expiredays, path, domain, secure) {
var exdate = new Date (); Get current time
Exdate.setdate (exdate.getdate () + expiredays); Expiration time
Document.cookie = c_name + "=" +//cookie name
Escape (value) +//Encode cookie value
((expiredays = null)? "": "; expires=" + exdate.togmtstring ()) +//Set expiration time
((Path = null)? '/': ';p ath= ' + path ' +//Set access Path
(domain = null)? ': ';d omain= ' + domain ' +//set access domain
(secure = null)? ': '; secure= ' + secure); Set whether to encrypt
};
Setcookie (' Test ', ' name=sheng;sex=men;lancer=dullbear ', 30);
Setcookie (' BB ', ' name=sheng;sex=men ', 30);
/* Get cookie*/
function GetCookie (c_name, index) {
var cookies = Document.cookie; Get Cookie Value
var cookielen = cookies.length; Get cookie length
if (Cookielen > 0) {//cookie is not empty
var C_start = cookies.indexof (c_name + ' = '); Lookup requires a cookie value to be in the cookie number
if (C_start >-1) {//cookie value exists
C_start + = c_name.length + 1; Get cookie value start serial number
var c_end = Cookies.indexof ('; ', C_start); Get cookie Value End serial number
if (c_end = = 1) {//When the cookie is the last one
C_end = Cookielen; Set cookie value ending serial number to cookie length
};
var cookiestr = unescape (cookies.substring (C_start, c_end)); Get Decode Cookie Value
var cookieobj = Cookiestr.split (';'); Split Cookie Value
index = ((index = null)? 0:index); To determine whether the index is passing a value
var goalobj = Cookieobj[index]; Indexed arrays
var goalstr = goalobj.split (' = ');
var getcook = goalstr[1]; Gets the cookie value that needs to be fetched
return getcook;
};
} else {
Console.log (' page without Cookie ');
}
};
Alert (GetCookie (' test ', 0)); Print Query Cookie value