Javascript cookie proficiency

Source: Internet
Author: User

Cookies. Some people like them and some hate them. However, few really know how to use them. Now you can become a member of a few people-a cookie master who can be proud of himself.

If you have a bad memory like an author, you may not be able to remember people's names. When I met someone, I just nodded and asked, "Have you eaten !", And we expect greetings to end here. If you still need to express something, I have to turn to some tricky techniques to help me think about who the other person is. For example, people related to the other party, no matter how far the relationship between them is, as long as they can avoid the embarrassment of not remembering the name of the other Party: "How about mafester, the cute nephew of your neighbor next door?" In this way, I want to make the other Party feel that I really pay attention to him or her and even remember these things, even though the name is actually forgotten. However, it is not that I do not pay attention to it, but that my memory is really bad and there are too many names to remember. If I can set cookies for everyone, I will not commit this memory problem any more.

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 jim@support.microsoft.com. 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:

1. Use the user name and password to Log On Through SSL.

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

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

4. If Step 2 passes the check, check whether the time of the current time and logon time sound exceeds the allowed time length. If the user has timed out, the user is directed to the logon interface.

5. 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 mayArticleDescribes how to use Perl for Cookie management. 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 cookieName and Value

There are four other 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 http://www.zdnet.com/devhead/index.html creates a cookie. That is to say, any page in the http://www.zdnet.com/devhead/stories/articles can access the cookiebuilt at http://www.zdnet.com/devhead/index.html. However, what if http: // www.zdnet.com/zdnn/ needs to access the cookesset by http://www.zdnet.com/devhead/index.html? At this moment, weSet 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 http://www.zdnet.com/devhead/filters/ and http://www.zdnet.com/devhead/stories/to 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 zdnet.com. This is an extension of the path attribute. What if we want catalog.mycompany.com to access the cookies set by shoppingcart.mycompany.com? We can set the domain attribute to "mycompany.com" 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.

Cookies

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 formCodeIt 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]

<Value>, <date>, <domain>, and <path> should be replaced with the corresponding values. <Date> The GMT format should be used. You can use the. togmtstring () method of the date type date in the Javascript script language to obtain the date value in the 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 "mydomain.com" domain. The security status is secure.


// Date () constructor is set in milliseconds <br/> //. the return time of the gettime () method, in milliseconds <br/> // you must set the expiration time to 15 minutes, use 60000 ms to multiply by 15 minutes <br/> var expiration = new date ()). gettime () + 15*60000); <br/> document. cookie = "username =" + escape (form. username. value) + "; expires =" + expiration. togmtstring () + "; Path =" + "/" + "; _ domain =" + "mydomain.com" + "; secure ";

Reading cookies is a bit like a trick, because you get all the cookies in the current document at once.

// 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 we are interested in. 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. <Br/> function getcookie (cookie_name) <br/>{< br/> var allcookies = document. cookie; <br/> var cookie_pos = allcookies. indexof (cookie_name); </P> <p> // If an index is found, the cookie exists. <br/> // otherwise, the cookie does not exist. <Br/> If (cookie_pos! =-1) <br/>{< br/> // place cookie_pos at the beginning of the value. You only need to add 1 to the value. <Br/> cookie_pos + = cookie_name.length + 1; <br/> var cookie_end = allcookies. indexof (";", cookie_pos); </P> <p> If (cookie_end =-1) <br/>{< br/> cookie_end = allcookies. length; <br/>}</P> <p> VaR value = Unescape (allcookies. substring (cookie_pos, cookie_end); <br/>}</P> <p> return value; <br/>}</P> <p> // call the function <br/> 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

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.

External link

Each JavascriptProgramMembers should have a javascript: the definitive guide of David Flanagan. The cookie routines found in this book can help you encode more than one variable into a single cookie and overcome the "20 cookies per web server" restriction ". Please click this link to download this routine, ftp://ftp.oreilly.com/pub/examples/nutshell/JavaScript /.

Garbled processing for JS reading Chinese cookies written by ASP

JS can read and write cookies locally on the client side, but the Chinese content of the cookies written by ASP code on the server side may be garbled if Javascript is used locally. JS seems not very mature and intelligent enough. It has encountered many Chinese garbled characters in Js.

First, let's take a look at how to use js to read the cookie content. For convenience, directly post a JS post to read the cookie function code.

<textarea cols="50" rows="15" name="code" class="javascript:nogutter:nocontrols">Function getcookie (objname) {<br/> var arrstr = document. cookie. split (";"); <br/> for (VAR I = 0; I <arrstr. length; I ++) {<br/> var temp = arrstr [I]. split ("="); <br/> If (temp [0] = objname) return Unescape (temp [1]); <br/>}< br/>}</textarea>

The above JS function can be used to read the cookie content, and then there is a garbled problem. The cookie read from JS needs to be encoded and restored to a real Chinese content. Through the decodeuricomponent and escape functions, this is a system function of JS itself. The sample code is as follows:

VaR n = getcookie ('name'); // read cookie content
N = decodeuricomponent (escape (n); // handle Encoding Problems

N is the result of processing Garbled text. In fact, you can directly write the Garbled text into the function that reads the cookie.

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.