PHP独立Session数据库存储操作类分享

直接上代码:


代码如下:

class DbSession
{

const TYPE_INT = 1;
    const TYPE_STR = 2;

/**
     * Database configration
     *
     * @var array
     */
    private $_config = array(
            ‘host' => '127.0.0.1′,
            ‘port' => 3306,
            ‘username' => ‘root',
            ‘password' => ‘root',
            ‘dbname' => ‘db_mylab',
        ‘tablename' => ‘t_sessions',
        ‘cookie_prefix' => ‘mylab_',
        ‘cookiepath' => ‘/',
        ‘cookiedomain' => ”,
        ‘cookie_timeout' => 900
    );

/**
     * Table fields type array
     *
     * @var array
     */
    private  $_db_fields = array(
        ‘crc32sid'      => self::TYPE_INT,
                ‘sessionhash'   => self::TYPE_STR,
                ‘idhash'        => self::TYPE_STR,
                ‘userid'        => self::TYPE_INT,
                ‘ipaddress'     => self::TYPE_STR,
                ‘lastactivity'  => self::TYPE_STR,
                ‘location'      => self::TYPE_STR,
        ‘loggedin'      => self::TYPE_INT,
        ‘heartbeat'     => self::TYPE_STR
        );

/**
         * db obj
         *
         * @var mysqli object
         */
    private $_mysqli = null;

/**
     * Weather the session was created or existed previously
     *
     * @var bool
     */
    private $_created = false;

/**
     * Array of changes.
     *
     * @var array
     */
    private $_changes = array();

/**
     * @var bool
     */

private $_db_inited = false;

/**
     * session host
     *
     * @var string
     */
    private $_session_host = ”;

/**
     * session idhash
     *
     * @var string
     */
    private $_session_idhash = ”;

private $_dbsessionhash = ”;

private $_vars = array();

public function __construct()
        {
                $this->_dbsessionhash = addslashes($this->get_cookie(‘sessionhash'));

$this->_session_host = substr($_SERVER[‘REMOTE_ADDR'], 0, 15);

#This should *never* change during a session
            $this->_session_idhash = md5($_SERVER[‘HTTP_USER_AGENT'] . self::fetch_substr_ip(self::fetch_alt_ip()) );

$this->_init_config();
            $this->init_db();

$gotsession = false;

if ($this->_dbsessionhash)
            {
                $sql = ‘
                        SELECT *
                        FROM ‘ . $this->_config[‘tablename'] . ‘
                        WHERE   crc32sid = ‘ . sprintf(‘%u', crc32($this->_dbsessionhash)) . ‘
                            AND sessionhash = '‘ . $this->_dbsessionhash . ‘'
                                AND idhash = '‘ . $this->_session_idhash . ‘'
                        AND heartbeat > '‘ . date(‘Y-m-d H:i:s' ,TIMENOW – $this->_config[‘cookie_timeout']) . ‘'‘;
                    //echo $sql;exit;
                $result = $this->_mysqli->query($sql);
                $session = $result->fetch_array(MYSQLI_ASSOC);

if ($session AND ($this->fetch_substr_ip($session[‘ipaddress']) == $this->fetch_substr_ip($this->_session_host)))
                {
                        $gotsession = true;
                        $this->_vars = $session;
                        $this->_created = false;
                }
            }

if ($gotsession == false)
            {
                $this->_vars = $this->fetch_session();
                $this->_created = true;
                $gotsession = true;
            }

if ($this->_created == false)
            {
            $this->set(‘lastactivity', date(‘Y-m-d H:i:s', TIMENOW));
            $this->set(‘location', $_SERVER[‘REQUEST_URI']);
            }

}

/**
     * Builds an array that can be used to build a query to insert/update the session
     *
     * @return    array    Array of column name => prepared value
     */
    private function _build_query_array()
    {
        $return = array();
        foreach ($this->_db_fields AS $fieldname => $cleantype)
        {
            switch ($cleantype)
            {
                case self::TYPE_INT:
                    $cleaned = is_numeric($this->_vars["$fieldname"]) ? $this->_vars["$fieldname"] : intval($this->_vars["$fieldname"]);
                    break;
                case self::TYPE_STR:
                default:
                    $cleaned = "'" . addslashes($this->_vars["$fieldname"]) . "'";
            }
            $return["$fieldname"] = $cleaned;
        }

return $return;
    }

/**
     * Sets a session variable and updates the change list.
     *
     * @param    string    Name of session variable to update
     * @param    string    Value to update it with
     */
    public function set($key, $value)
    {
        if ($this->_vars["$key"] != $value)
        {
            $this->_vars["$key"] = $value;
            $this->_changes["$key"] = true;
        }
    }

public function get($key)
    {
        return $this->_vars["$key"];
    }

public function unsetchangedvar($var)
    {
        if (isset($this->_changes["$var"]))
        {
                unset($this->_changes["$var"]);
        }
    }

/**
     * Fetches a valid sessionhash value, not necessarily the one tied to this session.
     *
     * @return    string    32-character sessionhash
     */
    static function fetch_sessionhash()
    {
        return hash(‘md5′ , TIMENOW . rand(1, 100000) . uniqid() );
    }

private function _init_config()
        {
                $registry = Zend_Registry::getInstance();
                $config = $registry->get(‘config');
                $this->_config[‘host'] = $config->database->params->host;
        $this->_config[‘port'] = $config->database->params->port;
        $this->_config[‘username'] = $config->database->params->username;
        $this->_config[‘password'] = $config->database->params->password;
        $this->_config[‘dbname'] = $config->database->params->dbname;
        $this->_config[‘tablename'] = $config->database->session->tablename;

}

/**
         * initialize database connection
         */
        public function init_db()
        {
            if ($this->_db_inited)
            {
                return true;
            }

//mysqli_report(MYSQLI_REPORT_OFF);

$this->_mysqli = new mysqli(
                $this->_config[‘host'],
                $this->_config[‘username'],
                $this->_config[‘password'],
                $this->_config[‘dbname'],
                $this->_config[‘port']
            );

/* check connection */
                if (mysqli_connect_errno())
                {

// printf("Connect failed: %sn", mysqli_connect_error());
                    // echo ‘in ‘, __FILE__, ‘ on line ‘, __LINE__;
                    echo "{ success: false, errors: { reason: ‘ Connect failed: " . addslashes( mysqli_connect_error() ) . "' }}";
                    exit();

}

$this->_mysqli->query(‘set names latin1′);
            $this->_db_inited = true;

return true;
        }

/**
         * Fetches an alternate IP address of the current visitor, attempting to detect proxies etc.
         *
         * @return      string
         */
        static function fetch_alt_ip()
        {
                $alt_ip = $_SERVER[‘REMOTE_ADDR'];

if (isset($_SERVER[‘HTTP_CLIENT_IP']))
                {
                        $alt_ip = $_SERVER[‘HTTP_CLIENT_IP'];
                }
                else if (isset($_SERVER[‘HTTP_FROM']))
                {
                        $alt_ip = $_SERVER[‘HTTP_FROM'];
                }

return $alt_ip;
        }

/**
     * Returns the IP address with the specified number of octets removed
     *
     * @param    string    IP address
     *
     * @return    string    truncated IP address
     */
    static function fetch_substr_ip($ip, $length = null)
    {
        return implode(‘.', array_slice(explode(‘.', $ip), 0, 4 – $length));
    }

/**
     * Fetches a default session. Used when creating a new session.
     *
     * @param    integer    User ID the session should be for
     *
     * @return    array    Array of session variables
     */
    public function fetch_session($userid = 0)
    {
        $sessionhash = self::fetch_sessionhash();

$this->set_cookie(‘sessionhash', $sessionhash);

return array(
            ‘crc32sid'      => sprintf(‘%u', crc32($sessionhash)),
            ‘sessionhash'   => $sessionhash,
            ‘idhash'        => $this->_session_idhash,
            ‘userid'        => $userid,
            ‘ipaddress'     => $this->_session_host,
            ‘lastactivity'  => date(‘Y-m-d H:i:s', TIMENOW),
            ‘location'      => $_SERVER[‘REQUEST_URI'],
            ‘loggedin'      => $userid ? 1 : 0,
            ‘heartbeat'     => date(‘Y-m-d H:i:s', TIMENOW)
        );
    }

public function get_cookie($cookiename)
    {
        $full_cookiename = $this->_config[‘cookie_prefix'] . $cookiename;

if (isset($_COOKIE[$full_cookiename]))
        {
            return $_COOKIE[$full_cookiename];
        }
        else
        {
            return  false;
        }
    }

public function set_cookie($name, $value = ”, $permanent = 1, $allowsecure = true)
    {

if ($permanent)
        {
            $expire = TIMENOW + 60 * 60 * 24 * 365;
        }
        else
        {
            $expire = 0;
        }

if ($_SERVER[‘SERVER_PORT'] == '443′)
        {
            // we're using SSL
            $secure = 1;
        }
        else
        {
            $secure = 0;
        }

// check for SSL
        $secure = ((REQ_PROTOCOL === ‘https' AND $allowsecure) ? true : false);

$name = $this->_config[‘cookie_prefix'] . $name;
        $filename = ‘N/A';
        $linenum = 0;

if (!headers_sent($filename, $linenum))
        { // consider showing an error message if there not sent using above variables?
            if ($value == ” AND strlen($this->_config[‘cookiepath']) > 1 AND strpos($this->_config[‘cookiepath'], ‘/') !== false)
            {
                // this will attempt to unset the cookie at each directory up the path.
                // ie, cookiepath = /test/abc/. These will be unset: /, /test, /test/, /test/abc, /test/abc/
                // This should hopefully prevent cookie conflicts when the cookie path is changed.
                $dirarray = explode(‘/', preg_replace(‘#/+$#', ”, $this->_config[‘cookiepath']));
                $alldirs = ”;
                foreach ($dirarray AS $thisdir)
                {
                    $alldirs .= "$thisdir";
                    if (!empty($thisdir))
                    { // try unsetting without the / at the end
                        setcookie($name, $value, $expire, $alldirs, $this->_config[‘cookiedomain'], $secure);
                    }
                    $alldirs .= "/";
                    setcookie($name, $value, $expire, $alldirs, $this->_config[‘cookiedomain'], $secure);
                }
            }
            else
            {
                setcookie($name, $value, $expire, $this->_config[‘cookiepath'], $this->_config[‘cookiedomain'], $secure);
            }
        }
        else if (!DEBUG)
        {
            echo "can't set cookies";
        }
    }

private function _save()
        {
            $cleaned = $this->_build_query_array();

if ($this->_created)
            {
                //var_dump($cleaned);
                # insert query
                $this->_mysqli->query(‘
                        INSERT IGNORE INTO ‘ . $this->_config[‘tablename'] . ‘
                        (‘ . implode(‘,', array_keys($cleaned)) . ‘)
                    VALUES
                        (‘ . implode(‘,', $cleaned). ‘)
                ‘);
            }
            else
            {
                # update query
                $update = array();

foreach ($cleaned AS $key => $value)
            {
                if (!empty($this->_changes["$key"]))
                {
                    $update[] = "$key = $value";
                }
            }

if (sizeof($update) > 0)
            {
                $sql = ‘UPDATE ‘ . $this->_config[‘tablename'] . ‘
                        SET ‘ . implode(‘, ‘, $update) . ‘
                        WHERE crc32sid = ‘ . sprintf(‘%u', crc32($this->_dbsessionhash)) . ‘
                            AND sessionhash = '‘ . $this->_dbsessionhash . ‘'‘;
                //echo $sql;
                $this->_mysqli->query($sql);
            }
            }
        }

public function getOnlineUserNum()
        {
                $sql = ‘
                        SELECT count(*) as cnt
                        FROM ‘ . $this->_config[‘tablename'] . ‘
                        WHERE loggedin = 1
                          AND heartbeat > '‘ . date(‘Y-m-d H:i:s' ,TIMENOW – $this->_config[‘cookie_timeout']) . ‘'‘;

$result = $this->_mysqli->query($sql);
            $row = $result->fetch_array(MYSQLI_ASSOC);
                return $row[‘cnt'];
        }

private function _gc()
        {
                $rand_num = rand(); # randow integer between 0 and getrandmax()
                if ($rand_num < 100)
                {
                        $sql = ‘DELETE FROM ‘ . $this->_config[‘tablename'] . ‘
                                WHERE heartbeat < '‘ . date(‘Y-m-d H:i:s' ,TIMENOW – $this->_config[‘cookie_timeout']) . ‘'‘;

$this->_mysqli->query($sql);
                }
        }

public function __destruct()
        {
            $this->_save();
            $this->_gc();
            $this->_mysqli->close();
        }

}

(0)

相关推荐

  • php把session写入数据库示例

    复制代码 代码如下: <?phpclass session_handler { protected $maxlifetime = null; protected $dbHandle = null; public $config = null; public static function init($args) {  return new self($args); } public function __construct($args) { $this->config = $args;  $t

  • Session保存到数据库的php类分享

    复制代码 代码如下: <?php class SessionToDB { private $_path = null; private $_name = null; private $_pdo = null; private $_ip = null; private $_maxLifeTime = 0; public function __construct(PDO $pdo) { session_set_save_handler( array(&$this, 'open'), array(

  • php session 写入数据库

    本文实例介绍了php session 写入数据库的方法,分享给大家供大家参考,具体内容如下 <?php # # codeMaker Alpha 0.1.1 ( haowei.me ) # This framework comply with the GPL license agreement # class session_handler { protected $maxlifetime = null; protected $dbHandle = null; public $config = n

  • php实现将Session写入数据库

    使用session_set_save_handler()函数,将Session的内容写入数据库 <?php /* *@author Fahy *数据库为mysql, *数据库名为session,表名为session, *表中字段包括PHPSESSID,update_time,client_ip,data */ class Session{ private static $handler = null; private static $ip = null; private static $life

  • PHP将session信息存储到数据库的类实例

    本文实例讲述了PHP将session信息存储到数据库的类.分享给大家供大家参考.具体分析如下: SessionHandlerInterface接口是PHP内置的接口,直接实现就行了 具体可以看php手册关于session_set_save_handler函数的解释! PHP代码如下: 复制代码 代码如下: /** * session信息存储到数据库的类 * 表结构: * CREATE TABLE IF NOT EXISTS `sessioninfo` ( *  `sid` varchar(255

  • php基于session实现数据库交互的类实例

    本文实例讲述了php基于session实现数据库交互的类.分享给大家供大家参考.具体如下: <?php /** * session 数据库存储类 */ class Session { private static $session_id = 0; private static $session_data = array(); private static $is_update = FALSE; private static $is_del = FALSE; private static $is_

  • PHP封装的数据库保存session功能类

    本文实例讲述了PHP封装的数据库保存session功能类.分享给大家供大家参考,具体如下: PHP用数据库保存session类: <?php class SafeSessionHandler implements SessionHandlerInterface { public $save_path; public $session_name; public $table; public function __construct() { $this->table = new Table(&qu

  • 将PHP的session数据存储到数据库中的代码实例

    一个开发环境有多个网站,需要使用不同的session,解决方案很多.不过这次也高大上一把,用数据库存,方便以后扩展. PostgreSQL版 首先是数据库的部分 --drop table php_session create unlogged table php_session ( sess_id varchar(32) primary key, modify_time timestamp with time zone not null, sess_data varchar(3000) defa

  • php中使用session_set_save_handler()函数把session保存到MySQL数据库实例

    PHP保存session默认的是采用的文件的方式来保存的,这仅仅在文件的空间开销很小的windows上是可以采用的,但是如果我们采用uinx或者是liux上的文件系统的时候,这样的文件系统的文件空间开销是很大的,然而session是要时时刻刻的使用的,大量的用户就要创建很多的session文件,这样对整个的服务器带来性能问题. 另一方面,如果服务器起采用群集的方式的话就不能保持session的一致性,所以我们就绪要采用数据库的方式来保存session,这样,不管有几台服务器同时使用,只要把他们的

  • PHP用mysql数据库存储session的代码

    隐患一:如果客户端机器的cookie一旦因病毒而失效了,那么session也就相当于没有了. 隐患二:session在php中默认的是以文件的形式保存在一个临时文件夹里面的,对于一个小型系统来说,这样做完全可以, 可是对于一个大型而又被经常访问的系统来说,就不是很好的办法了.假设这个网站一天有1000个人访问.一个月以后session的临时文件夹就会有30000个临时文件.想象一下计算机要从30000里面找一条session_sid是一个多么漫长的事情呀! 因此为了提高效率. 交易使用用数据库保

随机推荐