php的Session和Cookie存储流程理解

1.Session执行流程

客户端请求服务器文件,代码举例如下:

session_start();
// 存储 session 数据
$_SESSION['views']=1;

这时候我们会发现,返回的头部信息中有个Set-Cookie参数

#响应头信息
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Type:text/html; charset=UTF-8
Date:Tue, 16 Jan 2024 05:47:05 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=50, max=1000
Pragma:no-cache
Server:Apache/2.4.39 (Win64) OpenSSL/1.1.1b mod_fcgid/2.3.9a mod_log_rotate/1.02
Set-Cookie:PHPSESSID=9hbl0meish08rs48m7s5nmfvf6; path=/
Transfer-Encoding:chunked
X-Powered-By:PHP/5.6.9


这时候会在服务器的 D:\phpstudy_pro\Extensions\tmp\tmp 目录下生成一个 sess_9hbl0meish08rs48m7s5nmfvf6 的文件

文件内容如下:

views|i:1;

再次访问该地址的时候,浏览器会自动带上cookie信息

#请求头信息
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.9
Cache-Control:max-age=0
Connection:keep-alive
Cookie:PHPSESSID=9hbl0meish08rs48m7s5nmfvf6
Host:e.523web.com
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1

2.存储位置

默认通过php.ini 配置文件进行配置,存储在服务上的某个目录下,比如

session.save_handler = files
session.save_path="D:\phpstudy_pro\Extensions\tmp\tmp"

也可以通过程序进行控制

//通过配置文件的path 进行配置
session_save_path($config['path']);

3.自定义会话机制

通过session_set_save_handler实现会话的自定义,举例如下

通过此方法可以实现用数据库或者redis进行session存储,这样可以避免集群环境下session的同步的问题

<?php

ini_set('session.gc_maxlifetime',10);

ini_set('session.gc_probability ' ,1);

ini_set('session.gc_divisor',5 );
class FileSessionHandler
{
    private $savePath;

    function open($savePath, $sessionName)
    {
        $this->savePath = $savePath;
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        echo __FUNCTION__."<BR>";
        return true;
    }

    function close()
    {
        echo __FUNCTION__."<BR>";
        return true;
    }

    function read($id)
    {
        echo __FUNCTION__."<BR>";
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    function write($id, $data)
    {
        echo __FUNCTION__."<BR>";
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }
        echo __FUNCTION__."<BR>";
        return true;
    }

    function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
                unlink($file);
            }
        }
        echo __FUNCTION__."<BR>";
        return true;
    }


    function end(){
        echo '我是最后脚本结束register_shutdown_functiond调用'."<br>";
    }
}

$handler = new FileSessionHandler();
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
);
// 下面这行代码可以防止使用对象作为会话保存管理器时可能引发的非预期行为
register_shutdown_function(array($handler,"end"));


session_start();
$_SESSION['name']='chenchao';
// session_commit();
// session_write_close(); // 如果开启,那顺序就是open read  (gc) write close
// session_destroy();
// session_regenerate_id(true);

4.Cookie 的存储流程

设置和读取cookie的php代码示例如下:

<?php
header('Content-type:text/html;charset=utf-8');
if(!$_COOKIE['name']){
    //setcookie()函数,添加cookie
    setcookie('age', '30', time() + 3600);
    setcookie('mobile', '15066158888', time() + 3600);
    var_dump(setcookie('name', 'chenchao', time() + 3600));
}else{
    //cookie已经存在则读取cookie
    echo $_COOKIE['name'];
}
?>

这时候会看到浏览器响应信息中有set-cookie的参数

Connection:Keep-Alive
Content-Type:text/html;charset=utf-8
Date:Wed, 17 Jan 2024 02:44:03 GMT
Keep-Alive:timeout=50, max=1000
Server:Apache/2.4.39 (Win64) OpenSSL/1.1.1b mod_fcgid/2.3.9a mod_log_rotate/1.02
Set-Cookie:age=30; expires=Wed, 17-Jan-2024 03:44:03 GMT; Max-Age=3600
Set-Cookie:mobile=15066158888; expires=Wed, 17-Jan-2024 03:44:03 GMT; Max-Age=3600
Set-Cookie:name=chenchao; expires=Wed, 17-Jan-2024 03:44:03 GMT; Max-Age=3600
Transfer-Encoding:chunked
X-Powered-By:PHP/5.6.9

再次访问会带上本地的cookie信息,发送给服务器,这样服务器就能获取我们的cookie数据了
请求信息内容如下:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Encoding:gzip, deflate
Accept-Language:zh-CN,zh;q=0.9
Cache-Control:max-age=0
Connection:keep-alive
Cookie:age=30; mobile=15066158888; name=chenchao
Host:e.523web.com
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36

cookie浏览器的保存位置
对应的文件保存位置目录是:
C:\Users\Administrator\AppData\Local\Google\Chrome\User Data\Default\Network
对应的文件名是 cookie
在这里插入图片描述

我用的是google浏览器,其他浏览器可能位置不一样
这个cookie文件可以用Navicat Premium 数据库客户端工具打开,打开后显示如下,乱码问题应该是加密了,这里不做探讨
在这里插入图片描述

  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

oraclechaozi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值