详解HTTP Cookie状态管理机制_php实例
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),否则存的是乱码

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.
