Reputation: 2617
I have made a simple website using Yii and I have used Yii-user extension. I have a separate php file on same server (lets name it loader.php).
I want to get current Yii logged in user in loader.php. I have realized that no session is set in Yii-user extension, then how can I do that?
Upvotes: 4
Views: 2854
Reputation: 65
I know this is 2 months old, but maybe someone else can find this helpful, i have the same problem, and thanks to creatoR i was able to get the solution, you can check it here How can i use session from yii framework into my 3rd party application
You should include yii.php and config file like this :
require('../../framework/yii.php');
$config = require('../../protected/config/main.php');
Than you need to do following:
Yii::createWebApplication($config);
and if you use var_dump like this you will get the info that you need, in this example is id,
var_dump(Yii::app()->User->id);
Upvotes: 3
Reputation: 2072
In Yii you can get user's ID by using this:
$userId = Yii::app()->user->Id;
It'll give user's ID, if user logined, and CWebUser object was saved in session.
In the process of initialization, CWebUser uses CWebUser->getState('__id') to get the ID of user, and, by default, It tries to get data from Yii's session. If you use Yii's default session component, CWebUser would look into $_SESSION[$key] for and ID, and the $key is:
CWebUser.php:567:
$key=$this->getStateKeyPrefix().$key;
CWebUser.php:540:
return $this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
So, your $key to get user_id from session is: md5('Yii.'.get_class($this).'.'.Yii::app()->getId()).
And what is Yii::app()->getId() ?
CApplication.php:232:
return $this->_id=sprintf('%x',crc32($this->getBasePath().$this->name));
So, in your "loader.php" you can use this to create a key for 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!";
I repeat: if you using default CSession component in yii, its easy to get user_id, but If you using some other class, for example, the one which using redis or mongoDB to store sessions instead of PHP's default mechanism - you'll have to make some more work to get data from this storages.
Upvotes: 1