search
HomeBackend DevelopmentPHP Tutorial《PHP核心技术与最佳实践》-Cookie-Session深入

  1. Cookie是在远程浏览器端存储数据并以此跟踪和识别用户的机制。在实现上COOKIE是存储在客户端的一小段数据,客户端(比如浏览器)通过HTTP协议和服务器端进行COOKIE交互,COOKIE是HTTP头的一部分(即先发送COOKIE然后才是DATA域),COOIE独立于语言,PHP对COOKIE的操作是通过HTTP协议的'COOKIE'字段来向客户端(比如浏览器)发送命令,具体的管理由客户端(浏览器)全程完成,PHP中的对COOKIE的操作函数的结果就是客户端操作的返回结果。
  2. JAVASCRIPT设置COOKIE会立即生效,而PHP设置的COOKIE不能立即生效而需等到下一个页面才能看到,这是因为设置的这个页面的COOKIE由服务器传递给客户浏览器,在下一个页面浏览器发给服务器的HTTP请求头的COOKIE域里才带有上一个页面设置的COOKIE变量。COOKIE没有显式的删除函数,想删除COOKIE则将COOKIE的expire设置为过期时间,这会自动触发浏览器的删除机制。
  3. 与header()函数一样,setcookie()函数也要在输出数据之前调用,因为HTTP中cookie域在data域的前面。
  4. setcookie有一个HttpOnly参数,如果设置了则JS脚本不能读取到COOKIE,但如果浏览器不支持HttpOnly则JS也能读取到COOKIE,这样做可加强安全但通过其他方法还是能看到的。每个域名下允许的COOKIE数目是有限且不固定的,超过了就删除旧的,COOKIE在请求的上行和下行都会产生流量,所以COOKIE不是越多越好。
  5. COOKIE保存方式有两种,一种是在文件中一种是保存在浏览器内在中,在浏览器内存中的随着浏览器的关闭会消除,而保存在文件中的不会,还有一种COOKIE是Flash创建的,称为Flash Shard Object,又称Flash Cookie,即使清空浏览器隐私数据COOKIE还是顽固的存在在硬盘上,因为它们不受浏览器管理而只爱Flash管理,一些网站采用这种技术识别用户。
  1. Session和Cookie在本质上没区别,都是针对HTTP协议(无状态的协议)的局限性而提出的一种保持客户羰和服务器保持会话连接状态的机制。PHP的SESSION默认通过文件的方式实现,妈存储在服务器端的SESSION文件,每个SESSION一个文件,文件名(sessionID)是随机的,sessionID会作为COOKIE域的一个字段在HTTP请求的上行和下行中来回传递,SESSION文件的一般内容结构如下:变量名 | 类型:长度:值。

  2. SESSION以文件形式分目录存放,分目录是因为当一个目录的文件数超过2000时读写这个目录就会很慢。SESSION的回收是被动的,为了保证能正常回收,可修改PHP配置文件中的session.gc_divisor参数以提高回收率(太大了会增加负载),或者设置一个变量判断是否过期。对于设置分组目录存储的SESSION,PHP不会自动回收,需要自己实现回收机制。

  3. SESSION存入数据库:大访问量的站点,用默认的SESSION存储方式不适合,较优的方法是用DB存取SESSION,解决这个问题的方案就是session_set_save_handler()函数,bool session_set_save_handler(callback open,callback close,callback read,callback write,callback destroy,callback gc),设置用于读写SESSION的回调函数,只需实现这几个接口PHP就能帮助我们进行SESSION管理。

  4. CREATE TABLE 'tableName' ('sid) CHAR(40) NOT NULL COMMENT 'session名','data' VARCHAR(200) NOT NULL COMMENT 'session值','update' INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '更新时间',UNIQUE INDEX 'sid' ('sid')) COLLATE = 'utf8_general_ci' ENGINE = MEMORY ROW_FORMAT = DEFAULT

    MEMORY引擎采用内在表,所有数据存储在内在,操作速度快,对于SESSION这种形式的数据正好适用。

    class SessionSaveHandle {

    public $lifeTime;

    public $tosql;

    public $db;

    private $sessiondata;

    private $lastflush;

    private $sessName = 'PHPSESSID';

    function open ($savePath,$sessionName) {return true;}

    function close () {return true;}

    function read ($sid) {}/ 根据$sid获取data并保存在$this->sessiondata中/

    function write ($sessID,$sessData) {} / 写SESSION,有则更新无则插入,返回布尔值/

    function destroy ($sessID) {}

    function gc ($sessMaxLifeTime) {} / 删除数据库里距上次更新时间比$sessMaxLifeTime大的SESSION/

    }

    ini_set('session.use_trans_sid',0);

    ini_set('session.use_cookie',1);

    ini_set('session.use_path','/');

    ini_set('session.use_save_handler','user');

    session_module_name('user');

    $session = new SessionSaveHandle();

    session_set_save_handler(array($session,"open"),array($session,"close"),array($session,"read"),array($session,"write"),array($session,"destroy"),array($session,"gc"),);

  5. 在大流量的网站中,SESSION存入DB存在效率不高、占据数据库connection资源等问题,可以使用Memcached/Redis等KETY-VALUE数据存储方式实现高并发、大流量的网站。

Statement
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
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

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.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment