Laravel中的中的Sessionid处理机制详解处理机制详解
主要给大家介绍了关于Laravel中Sessionid处理机制的相关资料,文中通过示例代码介绍的非常详细,对大家的
学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
前言前言
本文主要给大家介绍了关于Laravel中Sessionid处理机制的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看
看详细的介绍吧。
在 Laravel 的配置文件 config/session.php 中可以设置 Session Cookie Name,比如这个项目中设置名称为“sns_session”:
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => 'sns_session',
我们可以看到刷新页面,查看 cookie,会发现一个名称为 sns_session 的 cookie,名字就是我们自定义的。
这个 sessionid 就是 cookie 和 session 联系的桥梁,服务器通过这个 sessionid 判断来自哪个客户端的请求。
Laravel 的的 sessionid 每次刷新发生变化每次刷新发生变化
但是,每次刷新页面,这个 cookie 值都会发生改变!那么这样服务器如何保持会话呢?因为你的 sessionid 总是在变。
Laravel 对对 cookie 进行加密进行加密
我们在 vendor/laravel/framework/src/Illuminate/Session/Store.php 的 save 方法中调试一下,打印一下这里的调用栈:
/**
* {@inheritdoc}
*/
public function save()
{
$this->addBagDataToSession();
$this->ageFlashData();
$this->handler->write($this->getId(), $this->prepareForStorage(serialize($this->attributes)));
$this->started = false;
dd(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT,5));
}
每次刷新页面,这个 Store 对象的 id 属性其实是没有变化的,这个属性就是 sessionid 这个 cookie 的值。也就是
说,sessionid 的值并不是每次发生变化,而是写 cookie 的时候,值发生了变化。
在 vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php 中的 encrypt 方法找到了原因,这个中间
件对所有 cookie 值进行了加密处理,它被包含在 web 中间件。
protected function encrypt(Response $response)
{
foreach ($response->headers->getCookies() as $cookie) {
if ($this->isDisabled($cookie->getName())) {
continue;
}
$response->headers->setCookie($this->duplicate(
$cookie, $this->encrypter->encrypt($cookie->getValue())
));
}
return $response;
}
评论0
最新资源