【问题标题】:Get current user from Yii outside the website在网站外从 Yii 获取当前用户
【发布时间】:2014-03-13 19:14:42
【问题描述】:

我使用 Yii 制作了一个简单的网站,并使用了 Yii 用户扩展。我在同一台服务器上有一个单独的 php 文件(让我们将其命名为 loader.php)。
我想在 loader.php 中获取当前 Yii 登录用户。我已经意识到 Yii-user 扩展中没有设置会话,那我该怎么做呢?

【问题讨论】:

  • 为什么要投反对票?

标签: yii


【解决方案1】:

我知道这已经 2 个月大了,但也许其他人会觉得这很有帮助,我有同样的问题,感谢 creatoR,我能够得到解决方案, 你可以在这里查看 How can i use session from yii framework into my 3rd party application

你应该像这样包含 yii.php 和配置文件:

require('../../framework/yii.php');
$config = require('../../protected/config/main.php');

你需要做以下事情:

Yii::createWebApplication($config);

如果你像这样使用 var_dump,你会得到你需要的信息,在这个例子中是 id,

var_dump(Yii::app()->User->id);

【讨论】:

    【解决方案2】:

    在 Yii 中,您可以通过以下方式获取用户 ID:

    $userId = Yii::app()->user->Id;
    

    如果用户登录,它将给出用户的 ID,并且 CWebUser 对象保存在会话中。

    在初始化过程中,CWebUser 使用 CWebUser->getState('__id') 来获取用户的 ID,并且默认尝试从 Yii 的 session 中获取数据。如果你使用 Yii 的默认会话组件,CWebUser 会在 $_SESSION[$key] 中查找 ID,$key 是:

    CWebUser.php:567:
    $key=$this->getStateKeyPrefix().$key;
    
    CWebUser.php:540:
    return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
    

    因此,您从会话中获取 user_id 的 $key 是:md5('Yii.'.get_class($this).'.'.Yii::app()->getId())。

    什么是 Yii::app()->getId() ?

    CApplication.php:232:
    return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
    

    因此,在您的“loader.php”中,您可以使用它为 user_id 创建一个密钥:

    $basePath = "/var/www/yii-app.com/protected";//Place here your app basePath by hands.
    $app_name = "My super app";//Place here your real app name
    $app_id = sprintf('%x',crc32($basePath.$this->name));
    $class = "CWebUser";//Place here your real classname, if you using some other class (for example, I'm using my own implementation of the CWebUser class)
    $key = md5('Yii.'.$class.'.'.$app_id) . "__id";
    
    session_start();
    $user_id = $_SESSION[$key];
    echo "USER ID is:" . $user_id;
    //Now you can user $user_id in any way, for example, get user's name from DB:
    mysql_connect(...);
    $q = mysql_query("SELECT name FROM users WHERE id='" . (int)$user_id ."';";
    $data = mysql_fetch_array($q, MYSQL_ASSOC);
    echo "Hello, dear " . $data['name'] . ", please dont use this deprecated mysql functions!";
    

    我再说一遍:如果你在 yii 中使用默认的 CSession 组件,它很容易获得 user_id,但是如果你使用其他一些类,例如,使用 redis 或 mongoDB 来存储会话而不是 PHP 的默认机制的类 - 你'必须做更多的工作才能从这个存储中获取数据。

    【讨论】:

      猜你喜欢
      • 2021-01-13
      • 2013-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多