php基于redis處理session的方法
來源:易賢網(wǎng) 閱讀:785 次 日期:2016-07-20 15:18:42
溫馨提示:易賢網(wǎng)小編為您整理了“php基于redis處理session的方法”,方便廣大網(wǎng)友查閱!

這篇文章主要介紹了php基于redis處理session的方法的相關資料,需要的朋友可以參考下

一個基于redis的處理session的方法,如下。

<?php

class Session_custom {

  private $redis; // redis實例

  private $prefix = 'sess_'; // session_id前綴

  // 會話開始時,會執(zhí)行該方法,連接redis服務器

  public function open($path, $name) {

    $this->redis = new Redis();

    return $this->redis->connect("127.0.0.1",6379);

  }

  // 會話結束時,調用該方法,關閉redis連接

  public function close() {

    $this->redis->close();

    return true;

  }

  // 會話保存數(shù)據(jù)時調用該方法,在腳本執(zhí)行完或session_write_close方法調用之后調用

  public function write($session_id, $data) {

    return $this->redis->hMSet($this->prefix.$session_id, array('expires' => time(), 'data' => $data));

  }

  // 在自動開始會話或者通過調用 session_start() 函數(shù)手動開始會話之后,PHP 內部調用 read 回調函數(shù)來獲取會話數(shù)據(jù)。

  public function read($session_id) {

    if($this->redis->exists($this->prefix.$session_id)) {

      return $this->redis->hGet($this->prefix.$session_id, 'data');

    }

    return '';

  }

  // 清除會話中的數(shù)據(jù),當調用session_destroy()函數(shù),或者調用 session_regenerate_id()函數(shù)并且設置 destroy 參數(shù)為 TRUE 時,會調用此回調函數(shù)。

  public function destroy($session_id) {

    if($this->redis->exists($this->prefix.$session_id)) {

      return $this->redis->del($this->prefix.$session_id) > 0 ? true : false;

    }

    return true;

  }

  // 垃圾回收函數(shù),調用周期由 session.gc_probability 和 session.gc_divisor 參數(shù)控制

  public function gc($maxlifetime) {

    $allKeys = $this->redis->keys("{$this->prefix}*");

    foreach($allKeys as $key) {

      if($this->redis->exists($key) && $this->redis->hGet($key, 'expires') + $maxlifetime < time()) {

        $this->redis->del($key);

      }

    }

    return true;

  }

}

// 調用自定義的session處理方法

$handler = new Session_custom();

session_set_save_handler(

  array($handler, 'open'),

  array($handler, 'close'),

  array($handler, 'read'),

  array($handler, 'write'),

  array($handler, 'destroy'),

  array($handler, 'gc')

);

// 下面這行代碼可以防止使用對象作為會話保存管理器時可能引發(fā)的非預期行為,表示當腳本執(zhí)行之后或調用exit()之后,存儲當前會話數(shù)據(jù)并關閉當前會話

register_shutdown_function('session_write_close');

session_start();

// 可以使用session了

補充:

php.ini文件中的session.gc_probability與session.gc_divisor兩個配置選項共同決定gc函數(shù)調用的時機。默認值分為為1和1000,表示每個請求只有1/1000的機會調用gc函數(shù)。

以上就是本文的全部內容,希望對大家的學習有所幫助。

更多信息請查看網(wǎng)絡編程
易賢網(wǎng)手機網(wǎng)站地址:php基于redis處理session的方法

2025國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權所有:易賢網(wǎng)