What is a cookie
"A cookie is a variable stored in the visitor's computer. This cookie is sent whenever the same computer requests a page through the browser. You can use JavaScript to create and retrieve the value of the cookie." - w3school
A cookie is a file created by a visited website and is used to store browsing information, such as profile information.
From the perspective of JavaScript, cookies are some string information. This information is stored in the client's computer and is used to pass information between the client computer and the server.
This information can be read or set through document.cookie in JavaScript. Since cookies are mostly used to communicate between the client and the server, in addition to JavaScript, the server language (such as PHP) can also access cookies.
Cookie Basics
Cookies have size limits. The data stored in each cookie cannot exceed 4kb. If the length of the cookie string exceeds 4kb, this property will return an empty string.
Since cookies are ultimately stored in the client computer in the form of files, it is very convenient to view and modify cookies, which is why it is often said that cookies cannot store important information.
The format of each cookie is as follows: <cookie name>=<value>; both the name and value must be legal identifiers.
Cookies are valid for the period of time. By default, the life cycle of a cookie ends when the browser closes. If you want the cookie to be able to use after the browser is turned off, you must set the validity period for the cookie, which is the expiration date of the cookie.
alert(typeof document.cookie) The result is string. I used to think it was an array, and I made jokes...
Cookies have the concept of domain and path. Domain is the concept of domain. Because the browser is a security-conscious environment, different domains cannot access cookies from each other (of course, you can achieve cross-domain access through special settings). The path is the concept of routing. The cookies created by a web page can only be accessed by all web pages in the same directory or subdirectory as this web page, but cannot be accessed by other directories (this sentence is a bit confusing, it will be easy to understand after a while).
In fact, the way to create cookies is somewhat similar to the way to define variables, both require the use of cookie names and cookie values. Multiple cookies can be created on the same website, and multiple cookies can be stored in the same cookie file.
Cookie FAQ
There are two types of cookies:
The cookies set by the current website you are browsing
Third-party cookies from other domain sources such as embedding ads or images on web pages (the website can track your usage information by using these cookies)
The basic knowledge just mentioned the problem of the life cycle of a cookie. In fact, cookies can be roughly divided into two states:
Temporary cookies. During the current use process, the website will store some personal information, and the information will be deleted from the computer after the browser is closed.
Sets the cookie for the expiration time. Even if the browser is turned off, the information industry will still be in the computer. Such as the login name and password, there is no need to log in every time you go to a specific site. This cookie can be kept on the computer for several days, months, or even years
There are two ways to clear cookies:
Clear cookies through browser tools (there are third-party tools, and the browser itself also has this function)
Clear cookies by setting the validity period of cookies
Note: Deleting cookies may sometimes cause some web pages to fail to function properly
Browsers can accept and deny access to cookies through settings.
For functional and performance reasons, it is recommended to minimize the number of cookies used and to use small cookies as much as possible.
Details about cookie encoding will be introduced separately in the cookie advanced article.
If it is a page on the local disk, the Chrome console cannot use JavaScript to read and write cookies. The solution is...change a browser^_^.
Basic usage of cookies
1. Simple access operations
When accessing cookies using JavaScript, you must use the cookie attribute of the Document object; a line of code introduces how to create and modify a cookie:
The code copy is as follows:
document.cookie = 'username=Darren';
In the above code, 'username' represents the cookie name, and 'Darren' represents the value corresponding to this name. Assuming that the cookie name does not exist, then a new cookie is created; if it exists, the value corresponding to the cookie name is modified. If you want to create cookies multiple times, just use this method repeatedly.
2. Cookie reading operation
It is actually very simple to read cookies accurately, which is to operate on strings. Copy this code on w3school to analyze:
The code copy is as follows:
function getCookie(c_name){
if (document.cookie.length>0){ //First check whether the cookie is empty, if it is empty, return ""
c_start=document.cookie.indexOf(c_name + "=") //Check whether this cookie exists through indexOf() of the String object. If it does not exist, it is -1
if (c_start!=-1){
c_start=c_start + c_name.length+1 //The last +1 actually means the "=" number, so that the start position of the cookie value is obtained
c_end=document.cookie.indexOf(";",c_start) // Actually, when I saw the second parameter of indexOf(), I suddenly became a little dizzy. Later, I remembered that it indicates the specified starting index position... This sentence is to get the end position of the value. Because it is necessary to consider whether it is the last item, it is judged by whether the ";" number exists.
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end)) //The value is obtained through substring(). If you want to understand unescape(), you must first know what escape() does. They are all very important basics. If you want to know, you can search for it. The details of cookie encoding will also be explained at the end of the article.
}
}
return ""
}
Of course, there are many ways to implement cookies, such as arrays, regularities, etc., so I won't go into details here.
3. Set the validity period of cookies
The life cycle of cookies that often appear in articles is the validity period and the expiration period, that is, the time when the cookies exist. By default, cookies will be automatically cleared when the browser is closed, but we can set the validity period of cookies through expires. The syntax is as follows:
The code copy is as follows:
document.cookie = "name=value;expires=date";
The date value in the above code is a date-type string in GMT (Greenwich Time) format, and the generation method is as follows:
The code copy is 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 an instance of Date through new to get the current time;
getDate() method gets a day in the current local month, and then adds 30, which means I hope this cookie can be saved locally for 30 days;
Then set the time through the setDate() method;
Finally, use toGMTString() method to convert the Date object into a string and return the result
The following complete function illustrates the points we need to pay attention to when creating cookies. Create a function that stores information in a cookie:
The code copy is as follows:
function setCookie(c_name, value, expireds){
var exdate=new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
//Usage method: setCookie('username','Darren',30)
Now our function sets 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:
The code copy is as follows:
exdate.setHours(exdate.getHours() + expiredays);
This way, the validity period of cookies will be based on hours.
There are two ways to clear cookies in the FAQ. Now we want to say that cookies are invalidated by setting the validity period to an expired time. Since there is a method to set the expiration date, please ask interested friends to do it yourself^_^. Let’s continue with the deeper cookie topic below.
Cookie Advanced
One.cookie path concept
In the basics, there is a mention of the concept of cookies having domains and paths. Now let’s introduce the role of paths in cookies.
Cookies are usually created because users access the page, but this cookie is not accessible only on the page where the cookie is created.
By default, only web pages in the same directory or subdirectory as the page that created the cookie can be accessed. This is due to security considerations, not all pages can access cookies created by other pages at will. For example:
Create a cookie on the page "//www.VeVB.COM/Darren_code/", then the page under the path "/Darren_code/" such as: "//www.VeVB.COM/Darren_code/archive/2011/11/07/Cookie.html" can get cookie information by default.
By default, "//www.VeVB.COM" or "//www.VeVB.COM/xxxx/" cannot access this cookie (it is useless to just look at it, practice the truth^_^).
So how to make this cookie accessible to other directories or parent directories, you can achieve it by setting the path of the cookie. Examples are as follows:
The code copy is as follows:
document.cookie = "name=value;path=path"
document.cookie = "name=value;expires=date;path=path"
The red font path is the path of the cookie. The most common example is to let the cookie be in the directory, so that no matter which subpage is created, all pages can be accessed:
The code copy is as follows:
document.cookie = "name=Darren;path=/";
Two.cookie domain concept
The path can solve the problem of accessing cookies under the same domain. Let's continue to talk about the problem of accessing cookies between the same domain. The syntax is as follows:
The code copy is 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" share a related 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 to "/". example:
The code copy is as follows:
document.cookie = "username=Darren;path=/;domain=qq.com";
Note: It is definitely access between the same domain, and the domain value cannot be set to a domain name that is not the primary domain.
Three.cookie security
Usually, cookie information is used to pass data using HTTP connections. This method of delivery is easy to view, so the information stored in cookies is easily stolen. If the content delivered in the cookie is more important, then encrypted data transmission is required.
Therefore, the name of this attribute of the cookie is "secure", and the default value is empty. If the attribute of a cookie is secure, then data is transmitted between it and the server through HTTPS or other security protocols. The syntax is as follows:
The code copy is as follows:
document.cookie = "username=Darren;secure"
Setting cookies to secure only ensures that the data transmission process between the cookies and the server is encrypted, while the cookie file stored locally is not encrypted. If you want local cookies to be encrypted, you have to encrypt your data yourself.
Note: Even if the secure attribute is set, it does not mean that others cannot see the cookie information saved locally on your machine, so after all, just don’t put important information on cookies,...
Four.cookie encoding details
I originally wanted to introduce the knowledge of cookie encoding in the FAQ section, because if I don’t understand this, the encoding problem is indeed a pitfall, so I will talk about it in detail.
When entering cookie information, you cannot include special symbols such as spaces, semicolons, commas, etc., and in general, the storage of cookie information is in an unencoded manner. Therefore, before setting cookie information, you must first use the escape() function to encode the cookie value information, and when you get the cookie value, use the unescape() function to convert the value back. If setting cookies:
The code copy is as follows:
document.cookie = name + "="+ escape (value);
Let’s take a look at the sentence in getCookie() mentioned in the basic usage:
The code copy is as follows:
return unescape(document.cookie.substring(c_start,c_end));
In this way, you don’t have to worry about the cookie information error because a special symbol appears in the cookie value.
Personal code
The code copy is as follows:
/*Set Cookies*/
function setCookie(c_name, value, expiredays, path, domain, secure) {
var exdate = new Date(); //Get the current time
exdate.setDate(exdate.getDate() + expireds); //Expiration time
document.cookie = c_name + "=" + //cookie name
escape(value) + //Encoding the cookie value
((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + //Set expiration time
((path == null) ? '/' : ';path=' + path) + //Set the access path
((domain == null) ? '' : ';domain=' + domain) + //Set the access domain
((secure == null) ? '' : ';secure=' + secure); //Set whether to encrypt or not
};
setCookie('test', 'name=sheng;sex=men;lancer=dullbear', 30);
setCookie('bb', 'name=sheng;sex=men', 30);
/*Get Cookies*/
function getCookie(c_name, index) {
var cookies = document.cookie; //Get cookie value
var cookieLen = cookies.length; //Get cookie length
if (cookieLen > 0) { //When the cookie is not empty
var c_start = cookies.indexOf(c_name + '='); // Find the serial number required for cookie value in the cookie
if (c_start > -1) { //When the cookie value exists
c_start += c_name.length + 1; //Get the start sequence number of the cookie value
var c_end = cookies.indexOf(';', c_start); //Get the end sequence number of the cookie value
if (c_end == -1) { //When the cookie is the last one
c_end = cookieLen; //Set the end sequence number of the cookie value to the cookie length
};
var cookieStr = unescape(cookies.substring(c_start, c_end)); //Get the decoded cookie value
var cookieObj = cookieStr.split(';'); //Split cookie value
index = ((index == null) ? 0 : index); //Judge whether index is passed to a value
var goalObj = cookieObj[index]; //Index array
var goalStr = goalObj.split('=');
var getcook = goalStr[1]; //Get the cookie value that needs to be obtained
return getcook;
};
} else {
console.log('The page has no cookies');
}
};
alert(getCookie('test', 0)); //Print query cookie value