I have enabled session within my application like this (in config.php, components section):
'session' => array(
'class' => 'system.web.CDbHttpSession',
'connectionID' => 'db',
'timeout' => 86400,
'sessionName' => 'SOMEABSTRACT_PHPSESSID',
),
In UserIdentity I try to do this:
$_SESSION['userid'] = $model->id;
Which means that I will set that new session after I log in my user. But when I try to access the $_SESSION['userid'] or just $_SESSION — for reading — I get this exception:
Undefined variable: _SESSION
This is the way I'm trying to access this session array:
echo '<pre>';
die(var_dump($_SESSION, $_SESSION['userid']));
I don't have any clues about this, so my two simple questions for this issue are:
Why is this happening only when Yii's sessions are enabled and autoStart => true?
How to fix this?
PS I need this for CometChat integration with Yii framework.
You can have #session_start();. This will suppress the warnings if it session already starts and also set the variable like this Yii::app()->session['userid'] = $model->id; and retrieve the same with Yii::app()->session['userid'] wherever it is required.
Also you can set the logged in user like this after session start
$this->_id=$model->id;
$this->setState('title', $model->username);
$this->setState('role', $model->role);
Above are the default variables in yii for logged in users. To create new user entry in session you can have this Yii::app()->session['variablename']
Try like this, in your UserIdentity.php -
//After successfully authentication, create session
Yii::app()->session;
Yii::app()->session['userid'] = $user->id;
//Now you can get anywhere like this -
echo Yii::app()->session['userid'];
Related
I'm trying to implement a SessionProvider auth plugin for a mediawiki install.
I'm trying to integrate with an existing auth system that uses $_SESSION to indicate that a user is logged in, however any method I try, the resulting $_SESSION variable that I get inside the class' provideSessionInfo function is empty.
Previously this was done with a onUserLoadFromSession hook (that contained the bulk of the logic code below), but the update appears to have broken actually looking at the existing $_SESSION:
public function provideSessionInfo(WebRequest $request)
{
// $_SESSION is hidden away per-request, but $request->getSession likes to call this function (yay infinite loops)
if (!isset($_SESSION['memberid'])) {
return null;
}
$memberid = $_SESSION['memberid'];
$mr_user = MyRadio_User::getInstance($memberid);
$user = User::newFromName($memberid);
$dbr = wfGetDB(DB_REPLICA);
$s = $dbr->selectRow('user', ['user_id'], ['user_name' => $memberid]);
if ($s === false) {
return null;
} else {
$user->mName = $memberid;
$user->mId = $user->idForName();
$user->loadFromDatabase();
$user->saveSettings();
}
if ($mr_user->hasAuth(AUTH_WIKIADMIN) && !in_array('sysop', $user->getGroups())) {
$user->addGroup('sysop');
}
$user->mTouched = wfTimestampnow();
return new SessionInfo(SessionInfo::MAX_PRIORITY, [
'provider' => $this,
'persisted' => true,
'userInfo' => UserInfo::newFromUser($user, true),
]);
}
If I hardcode $memberid, the function and the session provider works fine, but I just can't seem to find a way to transfer the session from one PHP "application" to another.
Adding debugging shows the PHPSESSID variable still set in the cookie, but for whatever reason it can't be pulled out into an actual session object. I've tried various session_start() style methods to no effect.
I feel like I'm missing something obvious, but the documentation for this stuff is just a basic wiki page and the raw generated doxygen.
Session handling is not a good way of cross-application communication. MediaWiki uses its own session handling, which means there is no connection between $_SESSION in MediaWiki and $_SESSION in your application at all. The first will be populated from MediaWiki's object cache (as configured by $wgSessionCacheType), the other from PHP session files or whatever.
If you really do not have a better way to pass data, you'll have to write a custom access class which can be called by your provider, which will save the current session handler, install a null session handler (which restores PHP's native session handling which will hopefully be interoperable with the other application), start the session, fetch the session data, restore the original session handler, and probably start the session again.
I am using this link to use the cookies functionality in yii framework.
When I accessed the application in localhost it gives following error:
Property CWebApplication.Cookies is not defined.
Please help me guys that where I am doing mistake.
I have included
'Cookies' => array (
'class' => 'application.components.CookiesHelper'
),
in config->main.php and i am trying to use the function putCMsg
as follows
$this->putCMsg('someCookieName','SomeValue');
But this error comes on this line of index.php
Yii::createWebApplication($config)->run();
Creating cookie in config/main.php is not a good solution. It's better to set cookie in the controller's action like this:
$cookie = new CHttpCookie('someCookieName','SomeValue');
$cookie->expire = 200000; //times in milliseconds
I have looked all over and I can see where people have created the initial session for ZF2 auth, remember me's, etc, but I can't find where people are updating the session when there is activity. Basically, I already have an authentication (with doctrine) system and my current solution and I set up the following configuration setting:
return array (
'session' => array(
'cookie_lifetime' => 1800, // 30 min
'remember_me_seconds' => 1800, // 30 min
'use_cookies' => true,
),
);
Then what I am trying to do is RELOAD this on every request like this:
NOTE: I have code that only does this if the user is already logged in.
class Module
{
public function onBootstrap(EventInterface $e)
{
$this->getEventManager()->attach('route', array($this, 'onRoute'), -100);
}
public function onRoute(EventInterface $e)
{
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config['session']);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->rememberMe($config['session']['remember_me_seconds']);
$sessionManager->start();
}
}
My basic need is I'm trying to refresh the session (server and client) anytime there is a request, but 1. it feels like I'm re-creating it every time and 2. Sometimes the session seems to randomly die. I think this is because the original session dies after the 30 min I set it to.
Any advice?
PHP should be updating the session time for you, you don't need to do it manually.
Also, don't call rememberMe() on every request, as this will generate a new session token (assuming the session already exists).
I'm using Kohana 3 and I have an issue while logging in with an user.
I use this line to log in:
$success = Auth::instance()->login($_POST['login_user'], $_POST['login_password'], $remember);
And I got this error message:
Session_Exception [ 1 ]: Error reading session data. ~ SYSPATH/classes/kohana/session.php [ 326 ]
I have the sessions table created with the follow SQL:
CREATE TABLE `sessions` (
`session_id` varchar(24) NOT NULL,
`last_active` int(10) unsigned DEFAULT NULL,
`contents` text,
PRIMARY KEY (`session_id`),
KEY `sessions_fk1` (`last_active`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And also the session.php inside the config folder:
<?php defined('SYSPATH') or die('No direct script access.');
return array(
'database' => array(
/**
* Database settings for session storage.
*
* string group configuation group name
* string table session table name
* integer gc number of requests before gc is invoked
* columns array custom column names
*/
'group' => 'default',
'table' => 'sessions',
'gc' => 500,
'columns' => array(
/**
* session_id: session identifier
* last_active: timestamp of the last activity
* contents: serialized session data
*/
'session_id' => 'session_id',
'last_active' => 'last_active',
'contents' => 'contents'
),
),
);
?>
What might be the problem here?
Thanks!
I don't know if this will help, but I had a similiar problem.
The cause of this was that using one library (Facebook SDK), session was initialized on it's onw, and session handling was done using the $_SESSION variable. I noticed that there were two cookies - session (Kohanas session id) and PHPSESSID. This probably was the problems cause.
I modified the library so that id doesn't start the session on its own and the problem was solved.
So, you should probalby check if session isn't started elsewhere.
Session_Exception [ 1 ]: Error reading session data. ~ SYSPATH/classes/kohana/session.php [ 326 ]
Depends what version you're running, but this is caused by an exception being thrown when session data is being unserialized in read. You can see the bug report about it here: Session read errors not properly ignored. The solution would be to upgrade to the latest version if you haven't already.
Something else you need to look at is your session data. You'll have to see why your data is corrupt and can't be read properly. This could be an error generated from code in __sleep.
Workaround or solution for me was setting php.ini
session.auto_start = 0
Of course, restart your web-server
Not sure if you figured this out. But I had the same issue and it was related to my php config. I'm using NGNIX and php-fpm. By default my session files were trying to get saved to a directory that didn't exist. So I changed the session.save_path to a valid path and that fixed it.
One way to solve this is to instantiate a session instance before you create a Facebook SDK instance. For example:
$this->_session = Session::instance('native');
$this->_facebook = new Facebook(array(
'appId' => 'app_id',
'secret' => 'app_secret',
));
If you take a look at the code inside the constructor of the Facebook class you'll see it checks if a session has been started:
public function __construct($config) {
if (!session_id()) {
session_start();
}
parent::__construct($config);
if (!empty($config['sharedSession'])) {
$this->initSharedSession();
}
}
So if you create the session first it'll skip that block of code.
I have had such problems when switching to an online server (more than once :(, so it should be better put some clear guidance).
Recommendations:
§) If you are using Database session adapter:
Session::$default = 'database';
i.- Check that your DB credentials are correct.
ii.- Check that the table assigned to sessions data has correct type and size.
§) If you are using Encryption for your sessions data (config/session.php or config/.../session.php):
return array(
'cookie' => array(
// ...
'encrypted' => TRUE,
// ...
),
'database' => array(
// ...
'encrypted' => TRUE,
// ...
),
);
i- Check that you have mcryptinstalled:
$ php -m|grep mcrypt
mcrypt // installed
ii- Check that you are using the same key was used to encrypt data (config/encrypt.php or config/.../encrypt.php):
return array(
'default' => array(
'key' => 'yabadabadoo!',
'cipher' => MCRYPT_RIJNDAEL_128,
'mode' => MCRYPT_MODE_NOFB,
),
Workarounds
§) If is possible delete all sessions data and try again.
i) For native adapter: Delete all (or just the corresponding to your app) sessions files located in...
Stores session data in the default location for your web server. The
storage location is defined by session.save_path in php.ini or defined
by ini_set.
ii) For cookie adapter: Manually delete the sessions cookies in the browsers affected or programmatically (in case of many users affected): (PHP) How to destroy the session cookie correctly?
iii) For database adapter: TRUNCATE TABLE sessions (delete all records of sessions table)
So I need access to an existing Session from Zend. Don't ask why, I don't like to talk about it. Anyway, I've gotten as far as discovering that I can access it from the bootstrap before I initialize my session. I have the following code in place to attempt to pull it out and transfer it over:
protected function _initSession() {
session_start();
$values = $_SESSION;
session_write_close();
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' =>'localhost',
'username' => 'uname',
'password' => '******',
'dbname' => 'dbname'
));
Zend_Db_Table_Abstract::setDefaultAdapter($db);
$sessionConfig = array(
'name' => 'Sessions',
'primary' => 'sessionID',
'modifiedColumn' => 'lastModifiedTime',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime'
);
$saveHandler = new Zend_Session_SaveHandler_DbTable($sessionConfig);
Zend_Session::setSaveHandler($saveHandler);
Zend_Session::start();
$old = new Zend_Session_Namespace('OLD');
$old->values = $values;
}
It's choking when it hits Zend_Session::start(), claiming that a session has already been started. But I've called session_write_close() to close the session and as far as I can tell from my google-fu there's nothing wrong with restarting a previously cosed session. So why is it choking? Is it something specific to ZF? Is there something more I need to do to close the session? What gives?
You just can't.
Foremost, as described in the ZF documentation :
Do not use PHP's » session_start() function directly. If you use session_start() directly, and then start using Zend_Session_Namespace, an exception will be thrown by Zend_Session::start() ("session has already been started").
So your code must looks like that :
Zend_Session::start();
$values = $_SESSION;
Zend_Session::writeClose();
But in Zend/Session.php:418, we have :
if (self::$_sessionStarted && self::$_destroyed) {
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception('The session was explicitly destroyed during this request, attempting to re-start is not allowed.');
}
So, the way you do the things is unsupported by ZF (like suggested : either with two different requests or with a batch script).
I face same issue today, so I read your blog but still did research , so I find a way which I am sharing with you.
Just use php "session_start()" rather then "Zend_Session::start();"
"Zend_Session::start();" doesn't work after session close so you can go with php session_start();
If you find any good solution please update me :)