关于pHp的cookie与session在项目中使用问题
- 小白来问一个初级的问题,关于php的cookie与session问题
- cookie是保存在客户端的,session是保存在服务端的tmp目录下
- cookie大多数的使用场景是什么,因为http是无状态的,是否一般大型网站的会员登录都是cookie实现?
- 如果大型网站会员状态使用session实现,那么是不是不科学的?而且会影响服务器性能,再则就是这种基于文件型的session在遇到负载均衡时会找不到对应session
- 一般大型网站是否采用了基于redis或者memcache的cookie session ?
各位平时cookie,session使用最多的场景有哪些
回复内容:
- 小白来问一个初级的问题,关于php的cookie与session问题
- cookie是保存在客户端的,session是保存在服务端的tmp目录下
- cookie大多数的使用场景是什么,因为http是无状态的,是否一般大型网站的会员登录都是cookie实现?
- 如果大型网站会员状态使用session实现,那么是不是不科学的?而且会影响服务器性能,再则就是这种基于文件型的session在遇到负载均衡时会找不到对应session
- 一般大型网站是否采用了基于redis或者memcache的cookie session ?
各位平时cookie,session使用最多的场景有哪些
这位同学,如果这是你自己刚学COOKIE和session就想出来的问题,那真的很不错了。我学了好几年后才发现这些问题,真是惭愧啊。
cookie保存在客户端的,所以你可以用来保存对安全性要求不高的数据比如购物车和一些浏览记录等。这样可以从一定程度上缓解服务器的压力(相对session)。
登陆一般都是session的,关于你说的大型网站使用以文件的方式保存session是会拖慢运行速度(当一个文件夹下session文件过万后其查找效率将会特别低)。所以我们一般使用数据库和缓存技术来实现(像memcache和redis都是很好的解决方案)。在PHP中可以重新定义session的存取机制的。
PHP提供的SESSION机制使用简单,但缺点也是很明显的,比如实现购物车功能:
一个在手机上登录的用户,添加了多个商品到购物车.
当这个用户在电脑上登录后,并不能获取购物车里的内容,因为这两次登录的PHP SESSION的ID是不同的.
所以大多数网站,都是基于COOKIE和数据库实现身份验证和购物车等功能的.
先说身份验证,cookie里存用户ID和密码哈希,验证时根据ID查询数据库的用户密码,经过同样的哈希算法计算后,跟$_COOKIE里的密码哈希比对,一致则通过认证.然后就可以根据用户ID查询购物车数据表里的商品记录了.
当然,你也可以用COOKIE结合数据库实现类似PHP SESSION的机制,这里提供一个思路:
<code>online(sessid,session,time,version); CREATE TABLE `online` ( `sessid` int(10) unsigned NOT NULL DEFAULT '0', `session` varchar(20000) NOT NULL DEFAULT '', `time` int(10) unsigned NOT NULL DEFAULT '0', `version` int(10) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`sessid`), KEY (`time`), KEY (`version`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci; </code>
其中:
sessid是用户ID.
session存储用户会话,内容是会话数组serialize序列化后的串.
time是记录更新时间.
version是版本号,用于实现CAS(Check And Set)乐观锁.
读写函数:
<code>function cn_session_get($sessid) { CRUD($_COOKIE['myid'],online) + return unserialize($session); } function cn_session_set($sessid,$session) { serialize($session) + CURD_CAS_UPDATE } </code>
函数调用:
<code>$session = cn_session_get($sessid); echo $session['ip']; $session['ip'] = $_SERVER['REMOTE_ADDR']; cn_session_set($sessid,$session); 或者 register_shutdown_function(cn_session_set,$sessid,$session); </code>
cn_session_set()时用版本号version乐观锁进行冲突检测,保证session字段的数据完整性:
<code>cn_session_get: SELECT * FROM online WHERE sessid=1; cn_session_set: UPDATE online SET session=$session,version=last_version+1 WHERE id=1 AND version=last_version; </code>
如果没有更新记录,则返回AJAX操作失败的提示.
对比:PHP内置的会话机制使用的是排它锁(悲观锁).
session_start()开启的是一个对sess_ID会话文件的写保护锁,
其他页面操作同一个sess_ID会话文件的session_start()将会被阻塞,
直到请求完成或者用session_write_close()显式关闭.
这样的SESSION锁机制就避免了下面的情况:
A页面和B页面读取了相同的一份会话信息.
A页面修改并写入了会话变量a.
B页面随后也修改并写入了会话变量b.
这时B页面会覆盖了之前A页面写入的会话变量a.
注意:这种并发一般很少发生,所以基于数据库实现的会话机制使用乐观锁,也是合理的,并不会频繁遇到操作失败的情况.
会话应用场景:记录登录后的用户信息,购物车(读取/添加/删除),观看记录,验证码,csrf_token.
把购物车数据存以序列化或JSON串形式存到数据库字段中,也就丧失了SQL查询功能.
如果是以数据库记录的形式来存储购物车,则方便进行SQL查询.
cookie与session并用
session安全性高于cookie
但session耗费更高的服务器资源
小型站点无所谓,session即可
大型站点,可以在关键时刻用session。平时的用cookie
比如涉及到支付之类的用session登陆
比如点赞啊转发啊这些无所谓的操作,读cookie即可。
cookie在客户端存储,session在客户端存储凭证,在服务器端存储对应数据,所有牵扯到登录状态的验证用session,如果仅仅存储临时状态,比如说记录UI中菜单项位置,用cookie即可。

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

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
