What is the real difference between COOKIE and SESSION?

Source: Internet
Author: User
Tags set cookie
What is the real difference between COOKIE and SESSION?

COOKIE and SESSION comparison

 

1. the HTTP protocol itself is stateless.

We need to transmit information over HTTP to access the Internet. For example, if you enter http://www.sanyalanhua.com/in your browser and return to the Internet, you will find that the Internet is changed to http:/// www.sanyalanhua.com, because the web page is based on the http protocol. The http protocol does not record websites that users often access, their hobbies, and their ID accounts and passwords. This is the so-called stateless HTTP protocol. The HTTP protocol itself is stateless, which is consistent with the original purpose of the HTTP protocol. The client simply needs to request the server to download some files, there is no need to record the previous behavior of each other on both the client and server. Each request is independent, like a customer, a vending machine, or a common (non-membership) the relationships between supermarkets are the same. If you recognize them, they certainly cannot recognize you.

2. How do I understand cookies and sessions?

As cookies are closely related to sessions, we will introduce them here.

For example, when I was in Sanya, I often went to a deli to buy a duck with a mouth. In order to promote sales, the store's boss offered a free offer for every 10 purchases. In addition to the family's red and white invitations, should no one buy 10 roast ducks at a time? Therefore, the boss has to find a way to record the customer's consumption quantity. There are three solutions in total:

I. The boss remembers the consumption quantity of each customer, and will automatically send one when the customer consumes 10 items. This is like the HTTP protocol itself is stateful. You can remember the customer's activity behaviors. Unfortunately, for various considerations, the http protocol itself cannot be stateful, and the boss does not have such extraordinary memory, so this solution won't work!

II. The boss sends a credit card to the customer, which records the consumption quantity and generally has a validity period. Every time you buy roast duck, if the customer shows this card, the boss will know that the customer has visited the store. This approach is to maintain the status on the client, such as cookie technology. Open (windows System) C: \ Documents ents and Settings \ User Name \ Cookies, you will find some *. small txt files, which are cookies sent to you When you browse some websites ).

III. The boss sends a membership card to the customer. No information except the card number is recorded. If the customer shows the card every time he buys the roast duck, the boss moves out of the store's roster, find your card number and Add 1 point. This approach is to maintain the status on the server side.

It is like session technology.

The biggest difference between a cookie and a session is that a cookie sends a credit card to a customer, which records all the consumption information of the customer. Session is to send the accumulation token with only the card number (session id) to the customer, which records all the customer's consumption information. The Cookie is saved on the client, the session is saved on the server, and the session id is saved on the client, which is usually a small cookie file, this small file has nothing except the session id (like the card number), so it is much safer than cookie.

3. What is the use of cookies and sessions?

Common usage: for example, You need to log on to a member to download things on some websites. The http protocol itself is stateless and it cannot be known whether the customer has logged on. What should I do? Cookie and session will be known. For example, how does the shopping cart know which products have been selected by customers for online shopping? Cookies and sessions can also be recorded. All in all, cookie and session are technologies that can record the status of customers. Even though they are different technologies, session can be done as long as cookies can be done! COOKIE strategy

1. What is a cookie?

0 Cookie technology is a very controversial technology. Since its birth, it has become a focal point of debate among network users and Web developers. Some network users, even some senior Web experts, are also dissatisfied with its generation and promotion. This is not because of the weak functionality of Cookie technology or other technical performance reasons, it is only because they think that the use of cookies poses a threat to the privacy of network users. Because the Cookie is a small text file stored by the Web server in the user's browser, it contains information about the user (such as the ID number and password, the way the user purchases the website, or the number of times the user visits the site ).

So what about Cookie technology? Does it bring personal privacy hazards to network users? Let's take a look at the following content and try again.

In the development history of WEB technology, the emergence of Cookie technology is a major change. First, Netscape introduced Cookie technology in its Netscape Navigator browser. Since then, the World Wide Web Association began to support Cookie standards. In the future, it will be vigorously promoted by Microsoft (because the ASP technology adopted by Microsoft's IIS Web server uses Cookie technology to a large extent ), that is, Microsoft Internet Explorer fully supports Cookie technology. Up to now, most browsers support the Cookie technology or are at least compatible with the Cookie technology.

According to the definition in Netscape official documentation, Cookie is a method in which the server or script can maintain information on the customer's workstation under the HTTP protocol. Cookie is a small file stored on the user's browser by the Web server, it can contain information about the user (such as the ID number, password, the user's way of shopping on the Web site, or the number of times the user visits the site ). The Web site can access Cookie information whenever the User links to the server.

If you are using a windows system, open C: \ Documents ents and Settings \ USERNAME \ Cookies. You will find many small files in the *. txt format in this directory. That is, the cookie file. Of course, you may not be able to find anything in this directory, Because you installed a new system, never browsed the Internet, or disabled cookies in your browser. Otherwise, there will always be something in this directory.

In general, the browser uses one or more restricted files to support cookies. These files are called Cookie files on machines that use Windows operating systems and magic Cookie files on Macintosh machines. These files are used by websites to store Cookie data. Websites can insert information in these Cookie files, which has some side effects on some network users. Some users think that this has resulted in a violation of personal privacy. Worse, some users think that Cookie is an infringement of personal space and brings security hazards to users' computers.

Currently, some cookies are temporary, while others are continuous. Temporary cookies are only saved in the browser for a specified period of time. Once the specified period is exceeded, the Cookie will be cleared by the system. For example, in PHP, cookies are used to track user processes until the user leaves the website. A persistent Cookie is saved in the user's Cookie file, and can still be called when the next user returns.

When a Cookie is saved in a Cookie file, some users think that this will cause a big problem. Some users are worried that cookies will track users' online surfing habits, such as those types of websites and activities they love. Fear that once such personal information falls into the hands of some people with ulterior motives, the individual may become the object of a lot of advertising spam, or even be accidentally damaged. However, this worry will not happen because users outside the website cannot cross the website to obtain Cookie information. Therefore, it is impossible to apply cookies for this purpose. However, some browser developers have no choice but to make appropriate responses due to incorrect understanding of users and "pass by without authorization" (for example, Netscape Navigator4.0 and Internet assumer3.0 both provide Cookie blocking options ). I personally think that there is no wind and waves. If website programmers do not have a rigorous thinking, cookies do have some security problems, but these flaws are not enough to cover up the excellent quality of cookies, most people are still very happy to use it.

The long-awaited result of Cookie technology is that many browser developers are forced to provide flexible Cookie control functions in their browsers. For example, the two mainstream browsers Netscape Navigator and Internet Explorer process cookies in this way: Netscape Navigator4.0 can not only receive cookies for warning, but also shield them; internetExplorer3.0 can also block cookies. However, in Internet assumer4.0, you can only receive warnings and do not provide blocking options. However, in Versions later than Internet assumer4.0, the Cookie blocking option is added.

In addition, many of the latest technologies can even block cookies on browsers that cannot block cookies. For example, you can set Cookie files to different types to restrict the use of cookies. However, unfortunately, many website pages will be rejected if you want to completely block cookies. Today, many Web site developers fall in love with the powerful functions of Cookie technology. For example, the use of Session objects is inseparable from the support of cookies.

2. How does Cookie work?

When a customer accesses a PHP-based website, the setcookie function can be used in PHP to generate a cookie. After processing, the system sends the cookie to the client and stores it in C: \ Documents and Settings \ USERNAME \ Cookies directory. Cookie is part of the HTTP header, so the setcookie function must be called before any content is sent to the browser. This restriction is the same as the header () function (for details about head () function, refer to it ). When the customer visits the website again, the browser will automatically send the Cookies corresponding to the site under the C: \ Documents and Settings \ User Name \ Cookies directory to the server, the server automatically converts the cookie sent from the client into a PHP variable. In PHP5, the cookie sent from the client is converted to a global variable. You can use $ _ COOKIE ['xxx'] to read data.

Although there are still some network users who are happy with the Cookie debate today, the vast majority of network users are still inclined to accept cookies. Therefore, we do our best to use Cookie technology to develop our WEB pages.

3. Common Cookie Functions

● The SetCookie function creates a Cookie and attaches it to the end of the HTTP header. Note that Cookie is part of the HTTP header and is used to transmit information between the browser and the server. Therefore, the SetCookie function must be called before any HTML file's content is output, no space or blank rows are allowed before calling this function. If setCookie () recognizes second, no element can recognize first. The premise of using the setcookie () function is that the customer's browser supports cookies. If the customer disables this function, setcookie () is useless.

Int SetCookie (string name, string value, int expire, string path, string domain, int secure, bool httponly );

Parameter description:

Name; set the cookie variable name.

Value; set the cookie value.

Expire; set the cookie expiration time. If you want to save the cookie as a browser process, that is, it becomes invalid after the browser is closed. You can set expiretime to 0 directly. Eg: setcookie ("name", "value", 0 ). If this parameter is not set, closing the browser can also end a cookie.

Path: indicates the Directory on the web server, which is the directory of the called page by default. here is another note. For example, if your site has several different directories (such as a Shopping directory and a forum directory), if you only use cookies without paths, the Cookie set on the page under one directory is invisible on the page of another directory, that is, the Cookie is path-oriented. In fact, even if no path is specified, the WEB server will automatically pass the current path to the browser, and the specified path will force the server to use the set path. To solve this problem, add the path and domain name when you call SetCookie. The domain name format can be "http://www.phpuser.com/#, or" pai.phpuser.com ". The SetCookie function indicates the value part, which is automatically encoded during transmission. That is to say, if the value of "test value" is changed to "test % 20value" during transmission ", same as the URL method. Of course, this is transparent to programs, because PHP will automatically decode the Cookie value when receiving it.

Domain: the domain name that can be used by cookie. The default value is the domain name of the called page. This domain name must contain two ".", so if you specify your top-level domain name, you must use ".mydomain.com ". After the domain name is set, you must use this domain name to access the website cookie. If you use multiple domain names to access this page, this location can be empty or the domain name accessing this cookie is under one domain.

Secure: if it is set to "1", it indicates that the cookie can only be remembered by the user's browser as a secure server.

All parameters except name are optional. The value, path, and domain parameters can be replaced by an empty string "", indicating that they are not set. The expire and secure parameters are numeric and can be expressed as 0. The expire parameter is a standard Unix time mark, which can be obtained using the time () or mktime () function, in seconds. The secure parameter indicates whether the Cookie is transmitted over the network through the encrypted HTTPS protocol.

Httponly: if it is set to 1, it indicates that the cookie can only be used by the http protocol. Any script language, such as javascr Using pt, cannot obtain the cookie created by PHP, this effectively weakens attacks from XSS. (Note: This is only available in PHP5, and we have never used it. I have read the official manual to try translation. If you have any questions, please refer to the official manual .)

The currently set Cookie does not take effect immediately, but is not visible until the next page or refresh. this is because the Cookie is transmitted by the server to the client's browser on the configured page. After the next page or refresh, the browser can retrieve the Cookie from the client's machine and send it back to the server.

Gossip

Cookie application case:

● Create a cookie:

SetCookie ()

● Create a cookie array:

1:

SetCookie ("CookieArray []", "Value 1 ");

SetCookie ("CookieArray []", "Value 2 ");

Second:

SetCookie ("CookieArray [0]", "Value 1 ");

SetCookie ("CookieArray [1]", "Value 2 ");

● Receiving and processing cookies

PHP supports Cookie receiving and processing very well and is completely automatic. It is as simple as the GET and POST variables principle.

For example, if you set a Cookie named MyCookier, PHP will automatically analyze it from the HTTP header received by the WEB server and form a global variable that can be directly used, name: $ _ COOKIE ['mycooker']. The value of this variable is the Cookie value. Arrays also apply.

Examples are as follows: (assuming these are all set in the previous page and still valid)

Echo $ _ COOKIE ['mycooker'];

Example of getting a cookie array:

<? Php

// Create a cookie Array

Setcookie ("cookie [three]", "cookiethree ");

Setcookie ("cookie [two]", "cookietwo ");

Setcookie ("cookie [one]", "cookieone ");

// After the page is refreshed, use foreach to extract the cookie array.

If (isset ($ _ COOKIE ['cookies']) {

Foreach ($ _ COOKIE ['cooker'] as $ name => $ value ){

Echo "$ name: $ value <br/> \ n ";

}

}

?>

That's simple.

● Delete Cookie

There are two ways to delete an existing Cookie:

1. If only the SetCookie with the name parameter is called, the Cookie named this name will be deleted from the relationship host;

Setcookie ("MyCookie"); // Delete MyCookie.

2. Set the Cookie expiration time to time () or time ()-1 // time () Minus. It does not matter as long as it is the expiration time //, the Cookie is deleted after the page is viewed (in fact, it is invalid ). For example:

Setcookie ("MyCookie", "Value", time ()-1); // Delete MyCookie.

Note that when a Cookie is deleted, its value is still valid on the current page.

If you want to save the cookie as a browser process, that is, it becomes invalid after the browser is closed. You can set expiretime to 0 directly. For example, setcookie ("name", "value", 0 ). If this parameter is not set, closing the browser can also end a cookie.

Cookie considerations

1. There cannot be any html output before SetCookie (). It recognizes second, and no element dares to recognize first, that is, space, and no blank line can be used.

2. After SetCookie (), you can call echo $ _ COOKIE ["name"] on the current page without output. You must refresh or go to the next page to view the Cookie value. The reason is simple. After SetCookie () is executed, send a cookie to the client. If you do not refresh or browse the next page, how does the client send the cookie back to you? After the browser creates a Cookie, the Cookie will be carried in the Header for every request for the website. However, the Cookie will never be sent for requests from other websites. In addition, the browser will keep sending until the Cookie expires.

3. Cookie restrictions. A browser can create a maximum of 30 cookies, each of which cannot exceed 4 kb. Each WEB site can set a maximum of 20 cookies. (This is what I have seen in the book. It should be that a web site can create no more than 30 cookies. Otherwise, I would like to say a hundred cookies in my computer. Please advise me !)

4. Cookies are stored on the client. If you disable cookies, your cookies will naturally become useless! In the current browser, whenever we send a Cookie to the client, it intercepts it like a dog and asks the user whether to allow the Cookie to enter the door. Day, users are not experts. How many people know what Cookie is? If not, the virus is rejected.

 

Original address: http://www.cnblogs.com/sanyalanhua/archive/2010/03/02/1676468.html? Login = 1

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.