Home > Backend Development > PHP Tutorial > HTTP state management mechanism Cookie, state mechanism cookie_PHP tutorial

HTTP state management mechanism Cookie, state mechanism cookie_PHP tutorial

WBOY
Release: 2016-07-12 09:00:49
Original
1003 people have browsed it

Cookie of HTTP status management mechanism, status mechanism cookie

1. Origin of cookie

Cookies were first invented by Netscape employee Lou Montulli in March 1993 and were later adopted by W3C. Currently, cookies have become a standard and are supported by all mainstream browsers such as IE, Chrome, Firefox, Opera, etc.

The birth of cookies is due to the inherent flaws of the HTTP protocol. HTTP is a stateless protocol. Once the request/response is completed, the connection between the client and the server will be closed, and new data needs to be established to exchange data again. connection. This means that the server cannot track the session from the connection, that is, the server does not know which client it is.


Some typical applications such as login/shopping cart cannot be implemented. For example, the products purchased by user A in the shopping mall should be placed in user A's shopping cart. No matter when user A purchases them, they belong to the same session and cannot be placed in user B or user C's shopping cart. , which does not belong to the same session.

The basic principle is as shown in the figure

2. Cookie operation

The operations on cookies include the following

Note that cookies are mostly created on the server side. JS can also create cookies, but HttpOnly type JS cannot create them.

The cookie API (document.cookie) provided by the browser is too simple and can be encapsulated. For example, it is much more convenient to use the setter/getter cookie function as follows

/*
 * JS 写cookie和读cookie操作
 *
 * **取cookie**
 *   cookie(name)
 *
 * **写cookie**
 *   cookie(name, value)
 *   cookie(name, value, option)
 */
var cookie = function(name, value, option) {
	var doc = document
	if (value != undefined) { // set 
		option = option || {}
		if (value === null) {
			value = ''
			option.expires = -1
		}
		var expires = ''
		if (option.expires && (typeof option.expires == 'number' || option.expires.toUTCString)) {
			var date = new Date
			if (typeof option.expires == 'number') {
				date.setTime(date.getTime() + (option.expires * 24 * 60 * 60 * 1000))
			} else {
				date = option.expires
			}
			// for IE
			expires = '; expires=' + date.toUTCString()
		}
		var path   = option.path ? '; path=' + option.path : ''
		var domain = option.domain ? '; domain=' + option.domain : ''
		var secure = option.secure ? '; secure' : ''
		doc.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('')

	} else { // get 
		var cookieValue = null
		if (doc.cookie && doc.cookie != '') {
			var cookies = doc.cookie.split(';')
			for (var i = 0; i < cookies.length; i++) {
				var cookie = $.trim(cookies[i]).split('=')
				if ( cookie[0] == name && cookie.length > 1 ) {
					try {
						cookieValue = decodeURIComponent(cookie[1])
					} catch(e) {
						cookieValue = cookie[1]
					}
					break
				}
			}
		}
		return cookieValue
	}
};
Copy after login

Of course, there is also the more convenient https://github.com/florian/cookie.js, which provides more convenient functions.

 

3. Cookie type

For example, when testing the page on Sina Cloud: http://snandy.sinaapp.com/php/cookie.php, I planted 3 cookies, namely c1, c2, c3

$d1 = mktime(1,1,1,1,1,2018);
// 普通cookie
setcookie("c1", "Jack", $d1); 

// 安全的cookie,仅https,第6个参数
setcookie("c2", "John", $d1, NULL, NULL, TRUE); 

// HttpOnly cookie 第7个参数
setcookie("c3", "Resig", $d1, NULL, NULL, NULL, TRUE);
Copy after login

Visit with Firefox

I have three of them, saeut is from Sina Cloud.

Enter document.cookie

in firebug console

As you can see, c2 and c3 are inaccessible. c2 is a secure cookie and needs to be accessed under the https protocol. c3 is httpOnly and cannot be accessed by JS. This needs to be noted.

Change the access protocol to https: https://snandy.sinaapp.com/php/cookie.php, switch to firebug console and enter document.cookie, you can see c2 and you can access it

4. Cookie Pitfalls

1. When the cookies are too large or there are too many, an error will be reported when accessing the page. For example, the following prompt will appear.

Therefore, the site’s cookies need to be managed, and cookies cannot be planted at will. In addition, try to specify the path to limit the cookie to the specified range.

The website browsercookielimits.squawky.net records the cookie size of each browser

2. Unicode encoding (encodeURIComponent) is required when saving Chinese, otherwise the saved characters will be garbled

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1091269.htmlTechArticleHTTP status management mechanism Cookie, status mechanism cookie 1. Cookie origin cookie was originally an employee of Netscape, Lou Montulli Invented in March 1993 and later adopted by W3C, currently cookies...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template