PHP Session class similar to CodeIgniter Session Class?

前端 未结 2 1807
天命终不由人
天命终不由人 2021-01-25 06:10

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 sev

2条回答
  •  伪装坚强ぢ
    2021-01-25 06:49

    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 
     */
    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.

提交回复
热议问题