duanjue2576 2012-07-21 21:46
浏览 41

PHP Session类与CodeIgniter Session Class类似?

PHP session class similar to CodeIgniter session class? Exists?

I tried to search, but I did not get useful results. I was using CodeIgniter session class, that have several features a like so much:

Store user's unique Session Id, user's IP Address, user's User Agent data, last activity and other informations manually provided. Those informations are stored in a database (MySql). The class create a cookie to match the unique session id with the session id at the database. In my opnion, this class is very secure.

I want to use this class outside CodeIgniter (without using CodeIgniter). Can anyone recommend me a class with those features?

Thanks!

  • 写回答

2条回答 默认 最新

  • dragoninasia2014 2012-07-21 23:09
    关注

    Actually that are two pair of shoes: PHP Sessions and codeigniter sessions. It is good to know about the major differences and that is basically everything as in codeigniter the sessions did re-invent the wheel for large parts plus adding some features.

    So before you continue it's probably worth to take a look into the Session chapter in the PHP manual , PHP's build in session support is pretty powerful - but has not an object interface.

    For example to store PHP sessions into the database (default is the file-system), that is supported by a so called session save handler. Some PHP extensions offer a save-handler (e.g. memcache). Just to lighten your mind, this works with anything compatible with the memchache protocol, e.g. MySQL. But that is just one example. If you are looking for a session class, that is not related to native PHP sessions, add "PHP 3" to your search because before version 4, PHP had no native sessions and sure, others needed sessions, so they wrote their own libraries.

    Okay, to be sane, using PHP today, looking for sessions and saying that one don't want to touch PHP sessions is: just stupid. You might not want to touch the file-system, then store to cookies. You might not want to store to cookies, store to any store that is fast and server-side: memcached, mysql, couchdb, ssd file-system. Whatever. PHP native sessions are very flexible here:

    You can as well write your own user-land session save handler and store your session into the database. Actually any key-value store will do: The key is the session id, and the value is the encoded (serialized) session data. That is one binary string.

    As written next to the re-invention of the wheel codeigniter does, there are some features you might be looking for. Basically you can always take a look into the source-code of the session component of codeiginiter, it's not that complex. With a good IDE you can pick the stuff you want to inspect or just view it as inspiration.

    One feature is the meta-data codeigniter assigns to a session which for example is the remote address, the session start time (very useful) and the last activity (useful, too). You can pretty easily mimic that your own by storing this into the session each time you start (example below). For that you can create your own session object. The following is only a bare example, but it already has some nice features:

    • Creation of sessions
    • Meta-data like remote IP, creation and last activitiy timestamp.
    • Destroying of cookies if applicable.

    Usage:

    $session = new Session();
    $session['foo'] = 'bar';
    $session->destroy(); // yes, full destroy
    

    The code:

    /**
     * Session class
     *
     * @license MIT
     * @license-year 2012
     * @license-copyright-holder hakre <http://hakre.wordpress.com>
     */
    class Session implements ArrayAccess
    {
        private $meta = '__meta';
        private $started;
    
        public function __construct()
        {
            if (ini_get('session.auto_start')) {
                $this->started = true;
                $this->start();
            }
        }
    
        public function start()
        {
            $this->started || session_start();
            (isset($_SESSION[$this->meta]) || $this->init())
                || $_SESSION[$this->meta]['activity'] = $_SERVER['REQUEST_TIME'];
            $this->started = true;
    
        }
    
        /**
         * write session data to store and close the session.
         */
        public function commit()
        {
            session_commit();
        }
    
        public function destroy()
        {
            $_SESSION = array();
            if (ini_get("session.use_cookies")) {
                $params = session_get_cookie_params();
                setcookie(session_name(), '', time() - 42000,
                    $params["path"], $params["domain"],
                    $params["secure"], $params["httponly"]
                );
            }
            session_destroy();
        }
    
        public function get($name, $default = NULL)
        {
            return isset($_SESSION[$name]) ? $_SESSION[$name] : $default;
        }
    
        /**
         * @return string
         */
        public function getName()
        {
            return session_name();
        }
    
        private function init()
        {
            $_SESSION[$this->meta] = array(
                'ip'       => $_SERVER['REMOTE_ADDR'],
                'name'     => session_name(),
                'created'  => $_SERVER['REQUEST_TIME'],
                'activity' => $_SERVER['REQUEST_TIME'],
    
            );
            return true;
        }
    
        /**
         * Whether a offset exists
         * @link http://php.net/manual/en/arrayaccess.offsetexists.php
         * @param mixed $offset
         * @return boolean true on success or false on failure.
         * The return value will be casted to boolean if non-boolean was returned.
         */
        public function offsetExists($offset)
        {
            $this->started || $this->start();
            return isset($_SESSION[$offset]);
        }
    
        /**
         * Offset to retrieve
         * @link http://php.net/manual/en/arrayaccess.offsetget.php
         * @param mixed $offset
         * @return mixed Can return all value types.
         */
        public function offsetGet($offset)
        {
            $this->started || $this->start();
            return $this->get($offset);
        }
    
        /**
         * Offset to set
         * @link http://php.net/manual/en/arrayaccess.offsetset.php
         * @param mixed $offset
         * @param mixed $value
         * @return void
         */
        public function offsetSet($offset, $value)
        {
            $this->started || $this->start();
            $_SESSION[$offset] = $value;
        }
    
        /**
         * Offset to unset
         * @link http://php.net/manual/en/arrayaccess.offsetunset.php
         * @param mixed $offset
         * @return void
         */
        public function offsetUnset($offset)
        {
            unset($_SESSION[$offset]);
        }
    }
    

    So to summarize: If you use PHP sessions, you use PHP sessions. They are powerful, but you might want to add your handling on top. The exemplary Session class above takes care about the session life-cycle: Init, Update and destruction. PHP iteself takes care of starting the factual session and also about saving it. Naturally, you can add a class for the session storage as well, but if you are concerned about performance and simplicity, normally this can all be configured within php.ini.

    Apart from this, there is more advanced stuff:

    • Regenerating session IDs (PHP supports that, so easy to add to the class or just call PHP's function)
    • Copying data from one session to another (PHP does not support this easily, it's worth to wrap such a feature into the session class if you need it - codeigniter does not have that, too)
    • Obtaining status if a session currently runs or not (the global PHP session). The Session class is a good place to add that if and only if you need it. You find the code in a related question: How to tell if a session is active?

    So, find out what you need. Implement as that, it can be pretty trivial. Write your own Session class wisely, feel free to use that one above as a base and add the features you need.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题