资讯专栏INFORMATION COLUMN

php如何实现session,自己实现session,laravel如何实现session

silvertheo / 3092人阅读

摘要:如何实现执行脚本,会从中读取配置项,将生成的唯一值保存文件放到配置项中的保存路径和地点。并通过协议返回响应消息头名值发送给客户端。

1、php如何实现session

</>复制代码

  1. 执行php脚本,session_start()会从php.ini中读取配置项,将生成的唯一值sessionID保存文件放到配置项中的保存路径和地点。并通过HTTP协议返回响应消息头setCookie
    Cookie名=Cookie值发送给客户端。

</>复制代码

  1. 客户端接受到Set-Cookie,将cookie值写入cookie文件

</>复制代码

  1. 在接下来的访问中,客户端会携带cookie访问浏览器,浏览器接受到cookie值,生成http请求头将包含的COOKIE发送给Php,php识别cookie值,从保存路径中找对应的文件。

</>复制代码

  1. 找到文件之后,检验是否在有效期内,在有效期内就读取文件,不再有效期内就清空文件
2、自己实现session需要考虑的几个问题 1)、生成唯一值的算法 2)、将session存到文件里还是存到redis还是memcache,应该存什么数据 3)、接受cookie值,从保存位置找到对应的文件或数据 4)、session垃圾回收机制,删除session文件和数据 5)、分布式的话,session同步问题 3、分析一下laravel如何实现session.

</>复制代码

  1. vendor/laravel/framework/src/Illuminate/Contracts定义都是接口类(契约)。向开发者提供了统一的接口类访问Session数据
    看一下session接口定义的是什么?

</>复制代码

  1. </>复制代码

    1. 实现接口类的具体实现类只有一个,也被称为驱动器
      vendor/laravel/framework/src/Illuminate/Session/Store.php
  2. </>复制代码

    1. </>复制代码

      1. class Store implements Session
      2. {
      3. protected $id;//session id
      4. protected $name;//session name
      5. protected $attributes = [];//session
      6. protected $handler;//会话处理程序实现,使用了sessionHandlerInterface接口
      7. protected $started = false;//会话存储处理状态
    2. </>复制代码

      1. public function __construct($name, SessionHandlerInterface $handler, $id = null)//创建一个新的session实例
      2. {
      3. $this->setId($id);
      4. $this->name = $name;
      5. $this->handler = $handler;
      6. //setId
      7. //$this->id = $this->isValidId($id) ? $id : $this->generateSessionId();
      8. //1、 $this->isValidId($id)?
      9. //return is_string($id) && ctype_alnum($id) && strlen($id) === 40;
      10. //is_string($id)检查sessionid是不是字符串,ctype_alnum检查sessionid所有的字符全是字母和数字,是为true,否为false;strlen检查字符串长度是否等于40
      11. //2、$this->generateSessionId();?
      12. //return Str::random(40); 这个使用Str门面类生成长度为40的唯一值
      13. //handler使用的是php预留接口类SessionnHandlerInterface,这个接口是为了将session存储到数据库中,(难怪在laravel查半天都没查到)。该类的回调方法是在php内部调用。
      14. }
    3. </>复制代码

      1. 来源于vendorlaravelframeworksrcIlluminateSupportStr.php
        laravel实现生成session唯一值算法函数,重点是使用了random_bytes函数和base64_encode函数
    4. </>复制代码

      1. public static function random($length = 16)
      2. {
      3. $string = "";
      4. while (($len = strlen($string)) < $length) {//当它的长度小于$length时
      5. $size = $length - $len;//长度差
      6. $bytes = random_bytes($size);//根据size生成加密安全的伪随机字节字符串
      7. $string .= substr(str_replace(["/", "+", "="], "", base64_encode($bytes)), 0, $size);//base64_encode对其进行编码,目的时为了使二进制数据可以通过非纯8比特的传输层传输,通过str_replace函数去掉字符串的/+=3种符号,在用substr截取$size大小的字符串。
      8. }
      9. return $string;
      10. }
    5. </>复制代码

      1. 来源于php手册中的关于SessionHandlerInterface接口的定义
    6. </>复制代码

      1. SessionHandlerInterface {
      2. /* 方法 */
      3. abstract public close ( void ) : bool
      4. abstract public destroy ( string $session_id ) : bool
      5. abstract public gc ( int $maxlifetime ) : int
      6. abstract public open ( string $save_path , string $session_name ) : bool
      7. abstract public read ( string $session_id ) : string
      8. abstract public write ( string $session_id , string $session_data ) :bool
      9. }
    7. </>复制代码

      1. 看看都有那些类实现了SessionHandler,在编程软件中全局搜索implements SessionHandlerInterface

        //CacheBasedSessionHandler 使用的实例化对象是
        Illuminate/Contracts/Cache/Repository
        "cache.store" => [IlluminateCacheRepository::class,
        IlluminateContractsCacheRepository::class],

      2. //CookieSessionHandler
        //DatabaseSessionHandler
        //FileSessionHandler
        //NullSessionHandler

    8. </>复制代码

      1. //根据session id读取数据
      2. public function start()
      3. {
      4. $this->loadSession();
      5. //验证csrf_token
      6. if (! $this->has("_token")) {
      7. $this->regenerateToken();
      8. }
      9. return $this->started = true;
      10. }
    9. </>复制代码

      1. protected function loadSession()
      2. {
      3. //array_merge合并两个数组
      4. //readFromHandler() 从驱动器中根据session id得到session信息
      5. $this->attributes = array_merge($this->attributes, $this->readFromHandler());
      6. }
    10. </>复制代码

      1. protected function readFromHandler()
      2. {
      3. if ($data = $this->handler->read($this->getId())) {
      4. //@阻止警告输出
      5. //unserialize反序列化读出来的session的id信息
      6. $data = @unserialize($this->prepareForUnserialize($data));
      7. //如果数组不是错误,不为空,是数组就返回数据
      8. if ($data !== false && ! is_null($data) && is_array($data)) {
      9. return $data;
      10. }
      11. }
      12. return [];
      13. }
    11. </>复制代码

      1. //返回数据
      2. protected function prepareForUnserialize($data)
      3. {
      4. return $data;
      5. }
    12. </>复制代码

      1. public function save()
      2. {
      3. $this->ageFlashData();
      4. $this->handler->write($this->getId(), $this->prepareForStorage(
      5. serialize($this->attributes)
      6. ));
      7. $this->started = false;
      8. }
    13. </>复制代码

      1. protected function prepareForStorage($data)
      2. {
      3. return $data;
      4. }
    14. </>复制代码

      1. //使会话闪存存数据老化
      2. public function ageFlashData()
      3. {
      4. $this->forget($this->get("_flash.old", []));
      5. //其他文件定义的forget方法
      6. > public static function forget(&$array, $keys)
      7. > {
      8. > $original = &$array;
      9. >
      10. > $keys = (array) $keys;
      11. >
      12. > if (count($keys) === 0) {
      13. > return;
      14. > }
      15. >
      16. > foreach ($keys as $key) {
      17. > // if the exact key exists in the top-level, remove it
      18. > if (static::exists($array, $key)) {
      19. > unset($array[$key]);
      20. >
      21. > continue;
      22. > }
      23. >
      24. > $parts = explode(".", $key);
      25. >
      26. > // clean up before each pass
      27. > $array = &$original;
      28. >
      29. > while (count($parts) > 1) {
      30. > $part = array_shift($parts);
      31. >
      32. > if (isset($array[$part]) && is_array($array[$part])) {
      33. > $array = &$array[$part];
      34. > } else {
      35. > continue 2;
      36. > }
      37. > }
      38. >
      39. > unset($array[array_shift($parts)]);
      40. > }
      41. > }
      42. $this->put("_flash.old", $this->get("_flash.new", []));
      43. $this->put("_flash.new", []);
      44. }
    15. </>复制代码

      1. public function all()
      2. {
      3. return $this->attributes;
      4. }
    16. </>复制代码

      1. public function exists($key)
      2. {
      3. $placeholder = new stdClass;
      4. return ! collect(is_array($key) ? $key : func_get_args())->contains(function ($key) use ($placeholder) {
      5. return $this->get($key, $placeholder) === $placeholder;
      6. });
      7. }
    17. </>复制代码

      1. //检查是否存在Key值
      2. public function has($key)
      3. {
      4. return ! collect(is_array($key) ? $key : func_get_args())->contains(function ($key) {
      5. return is_null($this->get($key));
      6. });
      7. }
    18. </>复制代码

      1. //获取session信息
      2. public function get($key, $default = null)
      3. {
      4. return Arr::get($this->attributes, $key, $default);
      5. }
    19. </>复制代码

      1. //删除,类似pop
      2. public function pull($key, $default = null)
      3. {
      4. return Arr::pull($this->attributes, $key, $default);
      5. }
    20. </>复制代码

      1. public function hasOldInput($key = null)
      2. {
      3. $old = $this->getOldInput($key);
      4. return is_null($key) ? count($old) > 0 : ! is_null($old);
      5. }
    21. </>复制代码

      1. public function getOldInput($key = null, $default = null)
      2. {
      3. return Arr::get($this->get("_old_input", []), $key, $default);
      4. }
    22. </>复制代码

      1. public function replace(array $attributes)
      2. {
      3. $this->put($attributes);
      4. }
    23. </>复制代码

      1. //session永久保存,在不过期范围内
      2. public function put($key, $value = null)
      3. {
      4. if (! is_array($key)) {
      5. $key = [$key => $value];
      6. }
      7. foreach ($key as $arrayKey => $arrayValue) {
      8. Arr::set($this->attributes, $arrayKey, $arrayValue);
      9. }
      10. }
    24. </>复制代码

      1. public function remember($key, Closure $callback)
      2. {
      3. if (! is_null($value = $this->get($key))) {
      4. return $value;
      5. }
      6. return tap($callback(), function ($value) use ($key) {
      7. $this->put($key, $value);
      8. });
      9. }
    25. </>复制代码

      1. //类似于push
      2. public function push($key, $value)
      3. {
      4. $array = $this->get($key, []);
      5. $array[] = $value;
      6. $this->put($key, $array);
      7. }
    26. </>复制代码

      1. public function increment($key, $amount = 1)
      2. {
      3. $this->put($key, $value = $this->get($key, 0) + $amount);
      4. return $value;
      5. }
    27. </>复制代码

      1. public function decrement($key, $amount = 1)
      2. {
      3. return $this->increment($key, $amount * -1);
      4. }
    28. </>复制代码

      1. //快闪保存,只保存两次请求
      2. public function flash(string $key, $value = true)
      3. {
      4. $this->put($key, $value);
      5. $this->push("_flash.new", $key);
      6. $this->removeFromOldFlashData([$key]);
      7. }
    29. </>复制代码

      1. public function now($key, $value)
      2. {
      3. $this->put($key, $value);
      4. $this->push("_flash.old", $key);
      5. }
    30. </>复制代码

      1. public function reflash()
      2. {
      3. $this->mergeNewFlashes($this->get("_flash.old", []));
      4. $this->put("_flash.old", []);
      5. }
    31. </>复制代码

      1. //刷新快闪数据时间,保持到下次请求
      2. public function keep($keys = null)
      3. {
      4. $this->mergeNewFlashes($keys = is_array($keys) ? $keys : func_get_args());
      5. $this->removeFromOldFlashData($keys);
      6. }
    32. </>复制代码

      1. protected function mergeNewFlashes(array $keys)
      2. {
      3. $values = array_unique(array_merge($this->get("_flash.new", []), $keys));
      4. $this->put("_flash.new", $values);
      5. }
    33. </>复制代码

      1. protected function removeFromOldFlashData(array $keys)
      2. {
      3. $this->put("_flash.old", array_diff($this->get("_flash.old", []), $keys));
      4. }
    34. </>复制代码

      1. public function flashInput(array $value)
      2. {
      3. $this->flash("_old_input", $value);
      4. }
    35. </>复制代码

      1. public function remove($key)
      2. {
      3. return Arr::pull($this->attributes, $key);
      4. }
    36. </>复制代码

      1. public function forget($keys)
      2. {
      3. Arr::forget($this->attributes, $keys);
      4. }
    37. </>复制代码

      1. //每次flush将数组置空
      2. public function flush()
      3. {
      4. $this->attributes = [];
      5. }
    38. </>复制代码

      1. public function invalidate()
      2. {
      3. $this->flush();
      4. return $this->migrate(true);
      5. }
    39. </>复制代码

      1. public function regenerate($destroy = false)
      2. {
      3. return tap($this->migrate($destroy), function () {
      4. $this->regenerateToken();
      5. });
      6. }
    40. </>复制代码

      1. //给session生成一个新的sessionID
      2. public function migrate($destroy = false)
      3. {
      4. //如果
      5. if ($destroy) {
      6. $this->handler->destroy($this->getId());
      7. }
      8. $this->setExists(false);
      9. $this->setId($this->generateSessionId());
      10. return true;
      11. }
      12. //是否启动
      13. public function isStarted()
      14. {
      15. return $this->started;
      16. }
      17. //获取session名
      18. public function getName()
      19. {
      20. return $this->name;
      21. }
      22. //设置session 名
      23. public function setName($name)
      24. {
      25. $this->name = $name;
      26. }
      27. //获取session id
      28. public function getId()
      29. {
      30. return $this->id;
      31. }
      32. //如果sessionid有效,就返回有效id,如果失效就生成session id
      33. public function setId($id)
      34. {
      35. $this->id = $this->isValidId($id) ? $id : $this->generateSessionId();
      36. }
      37. //检查session id
      38. public function isValidId($id)
      39. {
      40. return is_string($id) && ctype_alnum($id) && strlen($id) === 40;
      41. }
      42. //获取sessionID 唯一的40长度值
      43. protected function generateSessionId()
      44. {
      45. return Str::random(40);
      46. }
      47. //如果适用,在处理程序上设置会话的存在性
      48. public function setExists($value)
      49. {
      50. if ($this->handler instanceof ExistenceAwareInterface) {
      51. $this->handler->setExists($value);
      52. }
      53. }
      54. //获取token值
      55. public function token()
      56. {
      57. return $this->get("_token");
      58. }
      59. //生成唯一值40,存入_token
      60. public function regenerateToken()
      61. {
      62. $this->put("_token", Str::random(40));
      63. }
      64. //获取当前url
      65. public function previousUrl()
      66. {
      67. return $this->get("_previous.url");
      68. }
      69. //存储当前url
      70. public function setPreviousUrl($url)
      71. {
      72. $this->put("_previous.url", $url);
      73. }
      74. //获取当前使用的驱动器
      75. public function getHandler()
      76. {
      77. return $this->handler;
      78. }
      79. //返回驱动器实例是否使CokieSessionHandler
      80. public function handlerNeedsRequest()
      81. {
      82. return $this->handler instanceof CookieSessionHandler;
      83. }
      84. //如果驱动器是CookieSessionHandler,那么执行setRequest方法
      85. public function setRequestOnHandler($request)
      86. {
      87. if ($this->handlerNeedsRequest()) {
      88. $this->handler->setRequest($request);
      89. }
      90. }
      91. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/31633.html

相关文章

  • Laravel深入学习7 - 框架的扩展

    摘要:组件扩展通常有两种方法向容器中绑定自己的接口实现痛过使用工厂模式实现的类注册自己的扩展。类库管理类以工厂模式实现,负责诸如缓存等驱动的实例化。闭包须要传入继承自和容器的实例化对象。当完成扩展之后要记住中替换成自己的扩展名称。 声明:本文并非博主原创,而是来自对《Laravel 4 From Apprentice to Artisan》阅读的翻译和理解,当然也不是原汁原味的翻译,能保证9...

    yuanxin 评论0 收藏0
  • LaravelSession机制简介

    摘要:我们在这个类中的方法看到如下代码,一个典型的过滤器,在这个中获取的方法是。,整个初始化的过程总结下巧妙的使用了面向对象的接口方式,为我们提供了各种各样不同的存储方式,一旦我们了解了存储方式和加密规则,让不同的容器进行共享的目的也可以达到 前些天,为了解答一个问题,就去研究了Laravel的源码,讲讲我的收获:这个是问题源:http://segmentfault.com/q/101000...

    kelvinlee 评论0 收藏0
  • Laravel学习笔记之Decorator Pattern

    摘要:把和拼接在一起的场所是,所以需要造一个类,在其内部实现对的操作中实现了把原有的进过个的装饰后得到的新的,新的还是的实现,还是原来的物种。 说明:Laravel中Middleware的实现主要利用了Decorator Pattern的设计,本文主要先学习下Decorator Pattern如何实现,为后面学习Middleware的设计做个铺垫。Decorator Pattern和Adap...

    dendoink 评论0 收藏0
  • 详解 Laravel 中的依赖注入和 IoC

    摘要:依赖注入依赖注入一词是由提出的术语,它是将组件注入到应用程序中的一种行为。就像说的依赖注入是敏捷架构中关键元素。类依赖于,所以我们的代码可能是这样的创建一个这是一种经典的方法,让我们从使用构造函数注入开始。 showImg(https://segmentfault.com/img/remote/1460000018806800); 文章转自:https://learnku.com/la...

    haitiancoder 评论0 收藏0
  • Laravel学习笔记之Session源码解析(上)

    摘要:然后中间件使用方法来启动获取实例,使用类来管理主要分为两步获取实例,主要步骤是通过该实例从存储介质中读取该次请求所需要的数据,主要步骤是。 说明:本文主要通过学习Laravel的session源码学习Laravel是如何设计session的,将自己的学习心得分享出来,希望对别人有所帮助。Laravel在web middleware中定义了session中间件IlluminateSess...

    NervosNetwork 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<