PHP Session类类似于CodeIgniter Session类? [英] PHP Session class similar to CodeIgniter Session Class?

查看:54
本文介绍了PHP Session类类似于CodeIgniter Session类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP会话类是否类似于CodeIgniter会话类?存在吗?

PHP session class similar to CodeIgniter session class? Exists?

我尝试搜索,但没有得到有用的结果。
我使用的是CodeIgniter会话类,它具有多个
的功能,如:

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:

存储用户的唯一会话ID,用户的IP地址,
用户的用户代理数据,上次活动和手动提供的
其他信息。这些信息存储在数据库(MySql)中。
该类创建一个cookie,以将唯一的会话ID与数据库中的会话
ID匹配。
在我看来,此类非常安全。

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.

我想在CodeIgniter之外使用该类(不使用CodeIgniter)。
谁能推荐我一个具有这些功能的课程?

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

谢谢!

推荐答案

实际上这是两双鞋:PHP会话和codeigniter会话。很高兴知道主要的区别,基本上所有的事情都像在代码igniter中一样,会议确实重新发明了大型零件,并增加了一些功能。

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.

所以在此之前您继续阅读,可能值得研究一下PHP手册中的会话一章,PHP的内置会话支持功能非常强大-但没有对象接口。

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.

例如,将PHP会话存储到数据库中(默认为文件-系统),由所谓的支持会话保存处理程序 。一些PHP扩展提供了一个保存处理程序(例如memcache)。只是为了减轻您的想法,这可以与兼容memchache协议的任何东西一起使用,例如 MySQL 。但这只是一个例子。如果您正在寻找与本机PHP会话无关的会话类,请在搜索中添加 PHP 3,因为在版本4之前,PHP没有本机会话,并且肯定其他人需要会话,因此他们编写了自己的库。

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.

好吧,理智的今天使用PHP,寻找会话,并说不想接触PHP会话是:愚蠢的。您可能不想触摸文件系统,然后存储到cookie。您可能不想存储到cookie,存储到任何快速的服务器端存储:memcached,mysql,couchdb,ssd文件系统。随你。 PHP本机会话在这里非常灵活:

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:

您也可以编写自己的用户级会话保存处理程序并将会话存储到数据库中。实际上,任何键值存储都可以:键是会话ID,值是编码(序列化)的会话数据。那是一个二进制字符串。

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.

正如重新发明了车轮codeigniter所做的那样,您可能正在寻找一些功能。基本上,您始终可以查看 codeiginiter的会话组件,它并不复杂。有了一个好的IDE,您可以选择要检查的内容或将其视为灵感。

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:


  • 创建会话

  • 元数据,例如远程IP,创建和上次激活时间戳。

  • 销毁cookie(如果适用)。

用法:

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

代码:

/**
 * 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]);
    }
}

所以总结一下:如果您使用PHP会话,则可以使用PHP会话。它们功能强大,但您可能需要在上面添加处理功能。上面示例性的 Session 类关注会话生命周期:初始化,更新和销毁。 PHP iteself负责启动事实会话并保存它。当然,您也可以为会话存储添加一个类,但是如果您担心性能和简单性,通常都可以在php.ini中进行配置。

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:


  • 重新生成会话ID(PHP支持此功能,因此很容易添加到类中或只需调用PHP的功能)

  • 将数据从一个会话复制到另一个会话(PHP不轻松支持此功能,值得将这种功能包装到会话类 if 中)它-codeigniter也没有)

  • 获取当前状态(如果会话当前未运行)(全局PHP会话)。 Session 类是在需要时添加的好地方。您可以在以下相关问题中找到代码:如何判断会话是否处于活动状态?

  • 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?

所以,找出您需要的东西。那样实施,可能会很琐碎。明智地编写自己的Session类,可以随意使用上面的那个作为基础并添加您要使用的功能需要。

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.

这篇关于PHP Session类类似于CodeIgniter Session类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆