Working with the Yii framework in the config-file session storaged is handled as follows:
'session' => array(
//'sessionName' => 'SomeSession',
'class' => 'CDbHttpSession',
'connectionID' => 'SomeConnection',
'autoCreateSessionTable' => false,
'sessionTableName' => 'SomeTable',
'autoStart' => 'false',
'cookieMode' => 'only',
'useTransparentSessionID' => false,
'timeout' => CSESSIONTIMEOUT,
'cookieParams' => array(
'path' => '/',
'domain' => '.somedomain.extension',
'expire' => time()+5256000,
'lifetime' => time()+5256000,
//'httpOnly' => true,
),
),
So as you see sessions are stored in a table in a database with a given lifetime. But if I check the stored sessions in the database they are not stored with the given lifetime they are stored with a lifetime of a year.
The only thing I can find in our application that has a lifetime of a year are the cookies. For example like this:
setcookie("cookie_name", $someValue, time()+31536000, "/", "somedomain");
What is confusing for me are the cookies in our application. Could it be possible that this overrides the Yii session storage config?
UPDATE
I also came across this line of code
$_SESSION['POLL_'.$idPoll.'somekey'] = strtotime("now");
And that line of code inserted a session record in the database. But that record also has an lifetime of a year. How is this possible?
You need to add timeout param to config like this:
'session' => array(
'class' => 'CDbHttpSession',
'timeout' => 5256000,
// ...
Try Cookies Like this : -
if (isset($_POST['remember'])) {
$cookieUsername = new CHttpCookie('phoenix_admin_username', $_POST['LoginForm']['username']);
$cookiePassword = new CHttpCookie('phoenix_admin_password', base64_encode($_POST['LoginForm']['password']));
$cookieUsername->expire = time() + 604800;
$cookiePassword->expire = time() + 604800;
Yii::app()->request->cookies['phoenix_admin_username'] = $cookieUsername;
Yii::app()->request->cookies['phoenix_admin_password'] = $cookiePassword;
}
////////////Check like this//////////////
if(isset(Yii::app()->request->cookies['phoenix_admin_username'])){
$model->username = Yii::app()->request->cookies['phoenix_admin_username']->value;
$model->password = base64_decode(Yii::app()->request->cookies['phoenix_admin_password']->value);
}else{
$model->username = "";
$model->password = "";
}
Related
I write this below code in a different controller to store cookies
$cookies = Yii::$app->response->cookies;
$number=0;
if($cookies->has('registration_id')){
if($cookies->has('registration_attempt')){
$registration_att = $cookies->getValue('registration_attempt');
$number = $registration_att+1;
$cookies->add( new Cookie([
'name' => 'registration_attempt',
'value' => $number,
'expire' => time() + 86400*2,
]));
}
else{
$cookies->add( new Cookie([
'name' => 'registration_attempt',
'value' => $number,
'expire' => time() + 86400*2,
]));
}
} else{
$cookies->add(new Cookie([
'name' => 'registration_id',
'value' => 'Generate Id',
'expire' => time() + 86400*2,
]));
$cookies->add( new Cookie([
'name' => 'registration_attempt',
'value' => $number+1,
'expire' => time() + 86400*2,
]));
//**show here**
}
I set secure true but it does not show anything in different controller . When i am trying to access cookies value it shows null. Cookie value set but it doesn't set globally . Instant show cookie value where I commented show here. I am checking here if cookie set then if either else and always hit that. And if echo in that place it show data .
I want a "remember-me" cookie for my login form and get it work until I reopen the browser. I am using the Zend Framework 2 to get it done.
I set up a form with a checkbox and have this in my controller after validating the form:
$userSession = new Container("test");
$sessionManager = $userSession->getManager();
$sessionManager->rememberMe(1209600);
$sessionManager->start();
In the module.config.php I have the following settings for the session:
'session' => array(
'name' => 'Test_SESSION',
'save_path' => realpath('C:\xampp\htdocs\Workspace\test\data\session'),
'remember_me_seconds' => 1209600,
'cookie_lifetime' => 1209600,
'use_cookies' => true,
'cookie_httponly' => true,
),
And finally in module.php:
$session = new SessionConfig();
$session->setOptions($this->serviceLocator->get("config")["session"]);
I searched through the web for any advises and tried something, but at least when I close the browser the cookie is deleted. Firefox settings of deleting cookies were checked also, so they won't be automatically deleted. Does any one has a successful solution or hint?
Edit: When I take the code of newtake and add $sessionManager->rememberMe(); to it, the session is still alive after closing browser, but I can't login anymore even the login process is successfully done. Anyone heard from this curiosity?
Need setup SessionConfig to SessionManager. It is my config
'service_manager' => array(
'factories' => array(
'Zend\Session\SessionManager' => function ($sm) {
$sessionConfig = new \Zend\Session\Config\SessionConfig();
$sessionConfig->setOptions([
'use_cookies' => true,
'gc_maxlifetime' => 1728000,
'cookie_lifetime' => 1728000,
'name' => 'COOKIE_NAME',
]);
$sessionManager = new \Zend\Session\SessionManager($sessionConfig);
$sessionManager->start();
return $sessionManager;
}
)
)
My Website is for internal purpose, I have checked in all request if user session is there or not. but it get expire if user is idle,
I have set session like.
$time = 18000;
$config = new \Zend\Session\Config\StandardConfig();
$config->setGcMaxlifetime($time);
$config->setGcDivisor(100);
$config->setGcProbability(1);
$config->setRememberMeSeconds($time);
$sessionManager = new \Zend\Session\SessionManager($config);
$sessionManager->rememberMe($time);
but also it is expire in some minutes, pls help me to solve this.
I have spend lots of time in googling, but doesn't find any solution.
In principle, I avoid using cookie.
I use ZF1 and here is my setup:
In your example, the terms are the same and I'm sure you can adapt:
Add repertory for save your session (see APPLICATION_PATH . '/../tmp' in the code)
// Production
'session' => array( 'use_cookies' => true,
'use_only_cookies' => true,
'use_trans_sid' => false,
'strict' => false,
'remember_me_seconds' => 0,
'name' => 'MyNameSessionSession',
'gc_divisor' => 1000,
'gc_maxlifetime' => 600,
'gc_probability' => 1,
//'save_path' => APPLICATION_PATH . '/../tmp', // Not for production
),
// For Dev (Session No Limit)
$appli['resources']['session']['remember_me_seconds'] = 0;
$appli['resources']['session']['gc_divisor'] = 10;
$appli['resources']['session']['gc_maxlifetime'] = 8600;
$appli['resources']['session']['gc_probability'] = 1;
$appli['resources']['session']['save_path'] = APPLICATION_PATH . '/../tmp';
I hope it will help you, otherwise I'm sorry, i could'nt help you
Good luck :)
I am trying to change the default session time out value. In my controller i have done this:
public function beforeAction($action) {
$session = new CHttpSession;
$timeout = $session->getTimeout();
if ($timeout != 10) {
$session->setTimeout(10);
}
return true;
}
But my session never gets timed out an i can access the page even after being inactive for 10 sec.
I also tried to do it through config by session component like this:
'session' => array(
'sessionName' => SITE_SESSION_COOKIE_NAME,
'class' => 'CHttpSession',
'timeout' => 10
),
but same result. Session dosent time out! Am I missing out on something?
Try to turn off autostart session in configs:
'session' => array(
'sessionName' => SITE_SESSION_COOKIE_NAME,
'class' => 'CHttpSession',
'autoStart' => false
),
In this case you need manually starting session: Yii::app()->session->open(), but BEFORE IT for changing life time try do:
Yii::app()->session->open($session_lifetime);
$cook_p = Yii::app()->session->getCookieParams();
$cook_p['lifetime'] = $session_lifetime;
Yii::app()->session->setCookieParams($cook_p);
OR you may inherit CHttpSession with new parameter lifetime and do it in method init():
class MyHttpSession extends CHttpSession{
public $lifetime = false;
public function init()
{
if($this->lifetime !== false){
$cook_p = $this->getCookieParams();
$cook_p['lifetime'] = $this->lifetime;
$this->setCookieParams($cook_p);
$this->setTimeout($this->lifetime);
}
parent::init();
}
}
and in configs:
'session' => array(
'sessionName' => SITE_SESSION_COOKIE_NAME,
'class' => 'MyHttpSession',
'lifetime' => 60 // 1 minute
),
The class in the session array should apparently be CDbHttpSession for this to work.
See here for a similar issue..
for session timeout based on user being in-active for 30 minutes, in configs:
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=> true,
'autoRenewCookie'=> true,
'authTimeout' => 1800
),
'session' => array(
'class' => 'FrontCHttpSession',
'savePath' => dirname(__FILE__),
'cookieMode' => 'allow',
'cookieParams' => array(
'path' => '/',
'domain' => 'mydomain.com',
'httpOnly' => true,
'lifetime' => 1800
),
'timeout' => 1800
),
Extended session class, similar idea can be used for CDbHttpSession
<?php
class FrontCHttpSession extends CHttpSession
{
/*default is 0 which means the cookie lifetime will last as long as the browser is open*/
private $_clientLifetime;
/*time in seconds how long the session should remain open after user in-activity*/
private $_sessionTimeout;
/*cookie params defined in config*/
private $_cookieParams;
/**
* Starts the session if it has not started yet.
*/
public function open()
{
$this->_cookieParams = $this->getCookieParams();
$this->_clientLifetime = $this->_cookieParams['lifetime'];
$this->_sessionTimeout = $this->timeout;
if($this->getUseCustomStorage())
#session_set_save_handler(array($this,'openSession'),
array($this,'closeSession'),
array($this,'readSession'),
array($this,'writeSession'),
array($this,'destroySession'),
array($this,'gcSession'));
//session is already started, check if session has been not been active longer than timeout
if (session_id() != '')
{
if ($this->get('last_active') < time() - $this->_sessionTimeout)
{
$this->destroy();
}
else if ($this->_clientLifetime > 0)
{
$this->updateSessionCookieExpire();
}
}
#session_set_cookie_params($this->_clientLifetime, array($this->_cookieParams['path'],
$this->_cookieParams['domain'], $this->_cookieParams['secure'], $this->_cookieParams['httpOnly']));
#session_start();
$this->add('last_active', time());
if(YII_DEBUG && session_id()=='')
{
$message=Yii::t('yii','Failed to start session.');
if(function_exists('error_get_last'))
{
$error=error_get_last();
if(isset($error['message']))
$message=$error['message'];
}
Yii::log($message, CLogger::LEVEL_WARNING, 'system.web.CHttpSession');
}
}
public function updateSessionCookieExpire()
{
if (isset(Yii::app()->request->cookies[$this->getSessionName()]))
{
$c = Yii::app()->request->cookies[$this->getSessionName()];
$c->expire = time() + $this->_clientLifetime;
$c->path = $this->_cookieParams['path'];
$c->domain = $this->_cookieParams['domain'];
$c->httpOnly = $this->_cookieParams['httponly'];
$c->secure = $this->_cookieParams['secure'];
Yii::app()->request->cookies[$this->getSessionName()] = $c;
}
}
}
I am trying to set the max life time of a session with the \Zend\Session\Container. To test it I put it to 1 sec.
Now I looked at the docs
So i did
$config = new StandardConfig();
$config->setOptions(array(
'remember_me_seconds' => 1,
));
$manager = new SessionManager($config);
$session = new Container('user', $manager);
But no success. Then I started googling and found this answer
So I made the config to
return array(
'session' => array(
'remember_me_seconds' => 2419200,
'use_cookies' => true,
'cookie_httponly' => true,
),
);
(the config worked and was loaded into the manager) but again no success
So I continued searching and found this answer
But again no success.
So after all the searching I couldn't get it working, so now I hope some one else got it working and can help me.
Well I finaly found out what the issue was.
The problem was that I used
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions(array(
'use_cookies' => true,
'cookie_httponly' => true,
'gc_maxlifetime' => $config['authTimeout'],
));
$manager = new SessionManager($sessionConfig);
This "worked" the only issue was that there was set a cookie with the lifetime session. This ment different things in browsers. Ie in chrome it is destroyed if you close the tab, so no matter how high the gc_maxlifetime it would not work.
So an easy fix would be the following
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions(array(
'use_cookies' => true,
'cookie_httponly' => true,
'gc_maxlifetime' => $config['authTimeout'],
'cookie_lifetime' => $config['authTimeout'],
));
$manager = new SessionManager($sessionConfig);
Hope it would help some one in the futue
$config['authTimeout'] is a positive integer value
$config = new StandardConfig();
$config->setOptions(array(
'cookie_lifetime' => '2419200',
'gc_maxlifetime' => '2419200'
));
Change the value of 2419200 to how many seconds you actually want.
In application global.php or you can do it in module config:
'session_config' => array(
'name' => 'your session name',
'remember_me_seconds' => 60 * 60 * 24 * 30*3,
'use_cookies' => true,
'cookie_httponly' => true,
),
check Zend\Session\Service\SessionConfig.