HTTP cookies,通常又称作"cookies",已经存在了很长时间,但是仍旧没有被予以充分的理解。首要的问题是存在了诸多误区,认为cookies是后门程序或病毒,或压根不知道它是如何工作的。第二个问题是对于cookies缺少一个一致性的接口。尽管存在着这些问题,cookies仍旧在web开发中起着如此重要的作用,以至于如果cookie在没有可替代品出现的情况下消失,我们许多喜欢的Web应用将变得毫无用处。
一、cookie 起源
cookie 最早是网景公司的雇员 Lou Montulli 在1993年3月发明,后被 W3C 采纳,目前 cookie 已经成为标准,所有的主流浏览器如 IE、Chrome、Firefox、Opera 等都支持。
cookie 的诞生是由于 HTTP 协议的天生缺陷,HTTP 是一种无状态的协议,简单的 Request 和 Response 一旦请求/响应结束,客户端与服务器端的连接就会关闭,再次交换数据需要建立新的连接。这就意味着服务器无法从连接上跟踪会话,即服务器并不清楚是哪个客户端。
一些典型应用如 登陆/购物车 就无法实现了。比如,用户 A 在购物商城购买的商品都应该放在 A 的购物车内,不论是用户 A 什么时间购买的,这都是属于同一个会话的,不能放入用户 B 或用户 C 的购物车内,这不属于同一个会话。
基本的原理如图
二、cookie 操作
对 cookie 的操作包括如下
1.名称(Name)
2.值(Value)
3.域(Domain)
4.路径(Path)
5.失效日期(Expires)
6.安全标志(Secure)
7.HttpOnly (仅服务器端)
注意,cookie 多数时候由服务器端创建,JS 也可以创建 cookie,但 HttpOnly 类型的 JS 无法创建。
浏览器提供的 cookie API (document.cookie)实在过于简陋,可以稍封装下,如以下采用setter/getter方式 cookie 函数就方便了许多
/* * 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 } };
当然,还有更方便的 https://github.com/florian/cookie.js,提供了更多便捷函数。
三、cookie 类型
1.普通 cookie,服务器端和 JS 都可以创建,JS 可以访问
2.HttpOnly cookie,只能由服务端创建,JS 是无法读取的,主要基于安全考虑
3.安全的 cookie (仅https),服务器端和 JS 都可以创建,JS 仅HTTPS下访问
比如,在新浪云上测试页面:http://snandy.sinaapp.com/php/cookie.php,我种了 3 个 cookie,分别是 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);
用 Firefox 访问
我种的三个都有,saeut是新浪云种的。
在 firebug 控制台输入 document.cookie
可以看到,c2,c3 都是访问不到的。c2 是 安全的cookie,需要在https协议下访问,c3 则是 httpOnly 的,JS无法访问,这个需要注意。
把访问协议改成 https: https://snandy.sinaapp.com/php/cookie.php,firebug 切换到控制台再输入 document.cookie,可以看到 c2 就可以访问了
四、cookie 的坑
1. Cookie 太大或数量过多时页面访问报错,比如会出现如下提示
因此站点的 cookie 需要管理,不能随意种 cookie。另外尽量指定path,将cookie限定在指定范围内。
网站 browsercookielimits.squawky.net ,记录了各浏览器 cookie 大小
2. 保存中文时需要Unicode编码(encodeURIComponent),否则存的是乱码

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool