


Detailed explanation of HTTP Cookie state management mechanism, detailed explanation of cookie_PHP tutorial
Detailed explanation of HTTP Cookie state management mechanism, detailed explanation of cookies
HTTP cookies, often called "cookies", have existed for a long time, but are still not fully understood . The primary problem is that there are many misunderstandings, thinking that cookies are backdoors or viruses, or simply not knowing how they work. The second problem is the lack of a consistent interface for cookies. Despite these problems, cookies still play such an important role in web development that if cookies disappeared without a replacement, many of our favorite web applications would be rendered useless.
1. Origin of cookies
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
1.Name
2.Value
3.Domain
4.Path
5.Expires
6.Security
7.HttpOnly (server only)
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 } };
Of course, there is also the more convenient https://github.com/florian/cookie.js, which provides more convenient functions.
3. Cookie type
1. Ordinary cookies can be created by both server side and JS, and can be accessed by JS
2.HttpOnly cookie can only be created by the server and cannot be read by JS. It is mainly based on security considerations
3. Secure cookies (https only), both server-side and JS can be created, JS can only be accessed under HTTPS
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);
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 data will be garbled
Articles you may be interested in:
- Using Microsoft.XMLHTTP control to send COOKIE
- ASP uses XMLHTTP to implement form submission and cookie sending code
- AndroidHttpClient uses Cookie application analysis
- C# HttpClient Cookie verification solution
- Code for sending HTTP requests with cookies implemented using VBS
- .net Obtain browser cookies (including HttpOnly ) Example sharing
- The specific implementation of httpclient simulated login (using js to set cookies)
- Python imitates POST to submit HTTP data and use cookie values

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools