欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

memcache存储session 简单版本 实现功能了 空了来修改~

程序员文章站 2022-04-13 10:39:56
...
跳至
include('cls_session.php');
$m =new Memcache;
$m->connect('localhost',11211);    
$sess = new cls_session($m);

2. [代码][PHP]代码

session_name       = $session_name;

        $this->db  = &$db;
        $this->_ip = '127.0.0.1';

        if ($session_id == '' && !empty($_COOKIE[$this->session_name]))
        {
            $this->session_id = $_COOKIE[$this->session_name];
        }
        else
        {
            $this->session_id = $session_id;
        }

        if ($this->session_id)
        {
            $tmp_session_id = substr($this->session_id, 0, 32);
            if ($this->gen_session_key($tmp_session_id) == substr($this->session_id, 32))
            {
                $this->session_id = $tmp_session_id;
            }
            else
            {
                $this->session_id = '';
            }
        }

        $this->_time = time();

        if ($this->session_id)
        {

            $this->load_session();
        }
        else
        {

            $this->gen_session_id();

            setcookie($this->session_name, $this->session_id . $this->gen_session_key($this->session_id), 0);
        }

        register_shutdown_function(array(&$this, 'close_session'));
    }

    function gen_session_id()
    {
        $this->session_id = md5(uniqid(mt_rand(), true));

        return $this->insert_session();
    }

    function gen_session_key($session_id)
    {
        static $ip = '';

        if ($ip == '')
        {
            $ip = substr($this->_ip, 0, strrpos($this->_ip, '.'));
        }

        return sprintf('%08x', crc32(!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] . ROOT_PATH . $ip . $session_id : ROOT_PATH . $ip . $session_id));
    }

    function insert_session()
    {
    	$this->db->set(
    		$this->session_id,
    		array(
    			'ip'   => $this->_ip,
    			'time' => $this->_time, 
    		),
    		false,
    		$this->max_life_time
    	);
    	
    }

    function load_session()
    {
		$GLOBALS['_SESSION'] = $this->db->get($this->session_id);
    }

    function update_session()
    {
		$this->db->replace($this->session_id,$GLOBALS['_SESSION'],$this->max_life_time);
    }

    function close_session()
    {
    	$this->update_session();
    }

    function get_session_id()
    {
        return $this->session_id;
    }
    function destroy_session()
    {    
    	setcookie($this->session_name,'', 0);
    	$this->db->delete($this->session_id);
    }
}