Cookie Path and domain

Source: Internet
Author: User

What is cookies?

You will ask, what is cookies? Cookies are a small amount of data stored by browsers on users' computers. It is associated with a specific web page or website and automatically transmitted between the web browser and the web server.

For example, if you are running a Windows operating system and using Internet Explorer to access the Internet, you will find that there is a subdirectory named "Temporary Internet Files" under your "windows" directory ". If you have time to look at this directory, you will find some files in it. The file name looks like an email address. For example, in this directory on my machine, there is a file like This is a cookie file. Where does this file come from? Guess, it comes from Microsoft's support site. By the way, this is not my email address.

Cookies are a good solution for managing small and unimportant details that do not want to be stored in the central database. (This does not mean that everyone's name is not important .) For example, the increasing number of custom services on the website can be customized for each user. If you are designing a site like this, how do you manage this information: one user prefers a green menu bar, and the other one prefers a red menu bar. It is indeed a tiring question. However, such information can be recorded securely to cookies and stored on users' computers, and your own database space can be reserved for longer-term and more meaningful data.

FYI: cookies are usually useful for security purposes. I don't want to go too deep on this issue here. I just provide an example to see how to use cookies that expire after a period of time to ensure site security:

Use the user name and password to Log On Through SSL.
Check the username and password in the database on the server. If the logon succeeds, create a message digest (such as MD5) for the current time tag and save it in the cookie and server database. Save the user's logon time in the user records in the server database.
When performing each security transaction (any transaction in the user's login status), compare the cookie message digest with the digest saved in the server database. If the comparison fails, the user is directed to the logon interface.
If Step 1 passes the check, check whether the current time and logon time sound pass by exceeds the allowed time length. If the user has timed out, the user is directed to the logon interface.
If both steps 3rd and 4th pass, reset the logon time to the current time to allow transactions to occur. Most of the security sites that require you to log on may use a similar method as described here.
Cookie Composition

Cookies were originally designed for CGI programming. However, we can also use JavaScript scripts to manipulate cookies. In this article, we will demonstrate how to use JavaScript scripts to manipulate cookies. (If necessary, I may introduce how to use Perl for Cookie Management in future articles. But if it is not possible, I will teach you how to: take a closer look at CGI. PM. In this CGI package, there is a cookie () function that can be used to create a cookie. However, let's first introduce the nature of cookies.

In JavaScript scripts, a cookie is actually a string attribute. When you read the cookie value, you get a string containing the names and values of all cookies used on the current web page. Each Cookie has four attributes besides the name and value attributes. These attributes are: expires expiration time, Path, domain, and secure security.

Expires-expiration time. Specifies the life cycle of the cookie. Specifically, the value is the expiration date. This attribute is required if you want to allow the cookie to exist for more than the current browser session time. When the expiration date expires, the browser can delete the cookie file without any impact.

Path-path. Specifies the web page associated with the cookie. The value can be a directory or a path. If the creates a cookie. That is to say, any page in the can access the cookiebuilt at But what if the needs to access the cookesset in In this case, we need to set the path attribute of cookies to "/". When specifying a path, all web pages with the same path in the URL from the same server can share cookies. Now let's look at another example: if you want the and share cookies, you need to set the pathas #/devhead ".

Domain-domain. Specify the associated web server or domain. The value is a domain name, such as This is an extension of the path attribute. What if we want to access the cookies set by We can set the domain attribute to "" and the path attribute to "/". FYI: you cannot set the cookie domain attribute to a value different from the domain of the server on which it is set.

Secure-security. Specify how the cookie value is transmitted between the user and the Web server over the network. The value of this attribute is either "secure" or empty. By default, this attribute is null, that is, data is transmitted using an insecure HTTP connection. If a cookie is marked as secure, data is transmitted between it and the Web server over https or other security protocols. However, setting the secure attribute does not mean that others cannot see the cookies saved locally on your machine. In other words, setting the cookie as secure only ensures that the data transmission process between the cookie and the Web 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.


Remember that cookie is a string attribute of the document. To save the cookie, you only need to create a string in the format of name = <value> (name = value), and then set the document. Cookie of the document to be equal to it. For example, if you want to save the user name received by the form, the code looks like this:

Document. Cookie = "username" + escape (Form. username. Value); here, using the escape () function is very important because the cookie value may contain semicolons, commas, or spaces. This means that when reading the cookie value, you must use the corresponding Unescape () function to decode the value.

Of course, we also need to introduce the four attributes of cookies. These attributes are added to the string value in the following format:

Name = <value> [; expires = <date>] [; domain = <domain>] [; Path = <path>] [; secure]

Name = <value> [; expires = <date>] [; domain = <domain>] [; Path = <path>] [; security]

. Togmtstring () method to obtain the date value in GMT format. Square brackets indicate that this item is optional. For example, square brackets on the two sides of [; secure] indicate that "; secure" must be added after the cookie string value to set the cookie to secure. If "; secure" is not added to the cookie string, the cookie is insecure. Do not add the angle brackets <> and angle brackets [] to the cookie (unless they are the content of some values ). You can set attributes in any order.

In this example, the cookie "username" is set to expire after 15 minutes and can be accessed by all directories on the server, it can be accessed by all servers in the "" domain. The security status is secure.

// Date () constructor is set in milliseconds
//. Gettime () method return time, in milliseconds
// Set the expiration time to 15 minutes. The expiration time must be 60000 milliseconds and 15 minutes.
VaR expiration = new date (). gettime () + 15*60000 );
Document. Cookie = "username =" + escape (Form. username. Value) + "; expires ="
+ Expiration. togmtstring () + "; Path =" + "/" + ";_
Domain = "+" "+"; secure "; reading cookies is a bit like a trick, because you get all the cookies in the current document at a time.

// The following statement reads all cookies of the current document.
VaR allcookies = Document. Cookie; now, We have to parse the different cookies in the allcookies variable and find the specified cookies that interest us. This is easy because we can use the extended string support provided by the Javascript language.

If you are interested in the previously allocated cookie "username", you can use the following script to read its value.

// We define a function to read specific cookie values.
Function getcookie (cookie_name)
VaR allcookies = Document. Cookie;
VaR cookie_pos = allcookies. indexof (cookie_name );

// If an index is found, the cookie exists,
// Otherwise, it indicates that it does not exist.
If (cookie_pos! =-1)
// Put cookie_pos at the beginning of the value. You only need to add 1 to the value.
Cookie_pos + = cookie_name.length + 1;
VaR cookie_end = allcookies. indexof (";", cookie_pos );

If (cookie_end =-1)
Cookie_end = allcookies. length;

VaR value = Unescape (allcookies. substring (cookie_pos, cookie_end ));

Return value;

// Call a function
VaR cookie_val = getcookie ("username"); The cookie_val variable in the preceding routine can be used to generate dynamic content or send it to the CGI script on the server for processing. Now you know how to use JavaScript scripts to manipulate cookies. However, if you are like me, the first thing we need to do is to create some interface functions to hide the troubles of cookies processing. But wait a moment before you start programming. Someone has done these jobs for you long ago. All you have to do is find these interface functions.

For example, in David flangan's javascript: the definitive guide 3rd ed. Book, you can find a good cookie application class. You can also find examples in this book on the oreilly web site. In the link list at the end of this article, there are some direct links to access these cookie examples.


Cookies have a poor reputation for some reason. Many people use cookies to do mean things, such as traffic analysis and click tracking. Cookies are not very secure, especially those without the secure attribute. However, even if you use secure cookies, if you share a computer with others, such as an Internet cafe, then others can snoop unencrypted cookie files on the computer's hard disk, this may also steal your sensitive information. Therefore, if you are a web developer, consider these issues carefully. Do not abuse cookies. Do not store sensitive data in cookies. If a user's social security number or credit card number is stored in a cookie, the sensitive information is put under the window paper, which is tantamount to putting the user into great danger. A good principle is that if you don't want strangers to know your information, don't store them in cookies.

In addition, cookies have some actual restrictions. Cookies are retained on the computer and are not followed by the user. If you want to change the computer, the new computer cannot obtain the original cookie. Even if users use different browsers on the same computer, they cannot obtain the original COOKIE: Netscape cannot read Internet Explorer cookies.

In addition, users are reluctant to accept cookies. Therefore, do not accept cookies from all browsers. If the browser does not accept cookies, you must ensure that your web site will not crash or be interrupted.

In addition, the number of cookies retained by Web browsers may not exceed 300. There is no standard rule on when and how the browser will invalidate cookies. When the limit is reached, the browser can delete cookies randomly. The browser retains no more than 20 cookies from a Web server. The data (including names and values) of each cookie cannot exceed 4 kb. (However, the cookie size in this article is okay. It only occupies 12 kb and is stored in three 3 cookies .)

In short, keep the cookie simple. Do not rely on the existence of cookies. Do not store too much information in each cookie. Do not save too many cookes. However, in the hands of skilled Web administrators, the concept of cookie is a useful tool.

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: 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.