將Session寫下Memcache

來源:互聯網
上載者:User
將Session寫入Memcache

通過session_set_save_handler()方法自訂Session寫入Memcache

 1 php     2     class MemSession{ 3         private static $handler = null; 4         private static $lifetime = null; 5         private static $time = null; 6         const MS = 'session'; 7          8         private static function init($handler){ 9             self::$handler = $handler;10             self::$lifetime = ini_get('session.gc_maxlifetime');11             self::$time = time();12         }13         14         public static function start($memcache){15             self::init($memcache);16             //調用類中的方法要用數組,__CLASS__代表本類17             session_set_save_handler(18                 array(__CLASS__,'open'),19                 array(__CLASS__,'close'),20                 array(__CLASS__,'read'),21                 array(__CLASS__,'write'),22                 array(__CLASS__,'destroy'),23                 array(__CLASS__,'gc')24             );25             session_start();26         }27         28         public static function open($path,$name){29             30         }31         public static function close(){32             33         }34         35         public static function read($PHPSESSID){36             $val = self::$handler->get(self::session_key($PHPSESSID));37             38             if($val===false || $val==null){39                 return false;40             }41             return $val;42         }43         public static function write($PHPSESSID,$data){44             $method = $data? 'set':'replace';45             return self::$handler->$method(self::session_key($PHPSESSID),$data,MEMCACHE_COMPRESSED,self::$lifetime);46         }47         48         public static function destroy($PHPSESSID){49             return self::$handle->delete(self::session_key($PHPSESSID));50         }51         //memcache本身就有限定時間,資料自動銷毀,所以可不使用gc方法52         public static function gc($lifetime){53             return true;54         }55         56         //給sessionID加首碼,避免key重複57         private static function session_key($PHPSESSID){58             $session_key = self::MS.$PHPSESSID;59             return $session_key;60         }        61     }62     $mem = new Memcache;63     $mem->connect("localhost",11211) or die("could not connect");64     MemSession::start($mem);

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.