从网站外的Yii获取当前用户

时间:2013-08-20 18:27:53

标签: yii

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

2 个答案:

答案 0 :(得分:3)

我知道这是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);

答案 1 :(得分:1)

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

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

如果用户登录,它将提供用户的ID,并且会话中保存了CWebUser对象。

在初始化过程中,CWebUser使用CWebUser-> getState('__ id')来获取用户的ID,默认情况下,它尝试从Yii的会话中获取数据。如果您使用Yii的默认会话组件,CWebUser将查找$ _SESSION [$ key] for和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的默认机制 - 你'我必须做更多工作才能从这个存储中获取数据。