In ZF3, I'm initializing my session as following:
config/autoload/global.php
'session_config' => [
'name' => 'gintra3',
'cookie_lifetime' => 60*60*1,
'gc_maxlifetime' => 60*60*24*30,
],
'session_storage' => [
'type' => Zend\Session\Storage\ArrayStorage::class,
],
'session_manager' => [
'storage' => Zend\Session\Storage\SessionArrayStorage::class,
'validators' => [
Zend\Session\Validator\RemoteAddr::class,
Zend\Session\Validator\HttpUserAgent::class,
],
],
module/Application/Module.php
$sessionManager = $e->getApplication()->getServiceManager()->get(SessionManager::class);
$sessionTableGateway = new TableGateway('session',$e->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter'));
$sessionSaveHandler = new DbTableGateway($sessionTableGateway,new DbTableGatewayOptions());
$sessionManager->setSaveHandler($sessionSaveHandler);
Now, when I'm storing data like this on page 1:
$sessionC = new Container('test');
$sessionC->testVariable = "helloWorld";
And retrieve it on page 2 like this:
$sessionC = new Container('test');
Debug::dump($sessionC->testVariable);
I get an output on page 2 like this:
vendor/zendframework/zend-debug/src/Debug.php:97:null
When I check the database table, the 'data' column of the corresponding session_id contains "helloWorld" after loading page 1. After loading page 2, it does not contain "helloWorld" anymore.
If I comment out all session-related lines in Module.php, a PHPSESSID cookie is created on page load and session data saving and storing works fine now.
It does not matter if I use DbTableGateway as a save_handler or just use standard save_handler. The problem occurs in both cases.
When using my individual session storage, also FlashMessenger and Csrf-Form-Validation stop working due to the same mechanism of loosing all session data on page load.
Where is my problem? What am I overseeing?
Thanks a lot for some ideas.
Related
Where is session files stored in Yii2? I need to know the the exact location. There is options to create a session database.
The default session save path is '/tmp'. link
This path is accessible via the getSavePath() method in the session class file(yii2)
#property string $savePath The current session save path, defaults to '/tmp'.
For example, in xampp software (localhost) go to the following folder(default)
myDrive:\xampp\tmp // The drive where the software is installed
It is taken by default through the session_save_path method. Which depends on the settings of the php.ini file. In session.save_path="...\tmp"
But you can also configure it through the .htaccess file
To adjust Yii2, you can do the following. In the config web file
'components' => [
'session' => [
'name' => '_Session',
'savePath' => dirname(__DIR__) .'/sessions'
],
To save in the database(yii\web\DbSession) refer to this link.
Example:
'session' => [
'class' => 'yii\web\DbSession',
'name' => 'mySession',
// 'db' => 'mydb', // the application component ID of the DB connection. Defaults to 'db'.
// 'sessionTable' => 'my_session', // session table name. Defaults to 'session'.
'timeout' => 30 * 24 * 3600,
'cookieParams' => ['httponly' => true, 'lifetime' => 3600 * 24],
'writeCallback' => function ($session) {
return [
// 'user_id' => Yii::$app->user->id,
// 'last_write' => time(),
];
},
],
writeCallback: To create more data and columns in the database table
Good luck
Yii2 by default stores session files in #app/runtime/data folder.
And if you want to use database instead then yii2 guide is great resource. check this link: https://www.yiiframework.com/doc/guide/2.0/en/runtime-sessions-cookies#custom-session-storage.
I have time in seconds when the session should end. If the user has not selected the checkbox "remember_me" - the session will last 2 hours. When the checkbox is selected - should last - 48 hours. I have a loginСontroller, where I react - to the login result and if the validation is successful and checkbox = "on" you need to change the session time. I tried to change by looking at the documentation, and spent a lot of time looking for a solution. Maybe someone can help me. Thank you very much in advance[enter image description here]
here is my file config/app.php
'Session' => [
'defaults' => 'php',
'ini' => [
'session.cookie_lifetime' => 7200,
]
],
and here is my loginController
`public function index()
{
$this->viewBuilder()->setLayout('main');
$this->set("title", "");
$this->set("description", "description");
$this->request->allowMethod(['get', 'post']);
$result = $this->Authentication->getResult();
// regardless of POST or GET, redirect if user is logged in
if ($result->isValid()) {
if ($this->request->getData('remember') == 'on') {
///// the solution should be here
}
$redirect = [
'controller' => 'Main',
'action' => 'index',
];
return $this->redirect($redirect);
}
// display error if user submitted and authentication failed
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->saved_error(__('Invalid email or password'));
}
}`
You most likely shouldn't do it that way, your controller code shouldn't have to know about such details if it can be avoided.
The authentication plugin ships with a cookie based authenticator that you can use in addition to the session authenticator, that way you can extend authentication beyond the default session lifetime, I'd suggest that you look into that instead.
$service->loadAuthenticator('Authentication.Cookie', [
'fields' => $fields,
'loginUrl' => $loginUrl,
'cookie' => [
// cookie expires in 2 days from now
'expires' => \Cake\Chronos\Chronos::now()->addDays(2)
],
]);
By default the authenticator looks up a field named remember_me, so either rename that in your template, like:
echo $this->Form->control('remember_me', ['type' => 'checkbox']);
or configure the authenticator's rememberMeField option with the custom field name that you're using in your form.
See also
Authentication Cookbook > Authenticators > Cookie Authenticator
Hello i'd like to store some laravel sessions in once
so instead of doing like this :
// Storing Sessions
$request->session()->put('term', $request->term);
$request->session()->put('section', $request->section);
// Accessing Sessions
$request->session()->get('term');
$request->session()->get('section');
I want something like :
// Storing Sessions
$sessions = [
'term' => $request->term,
'section' => $request->section,
];
$request->session()->put($sessions);
// Accessing Sessions
$request->session()->get('term');
$request->session()->get('section');
But couldn't find the way.
I tried something like this , but the code for accesssing is ugly and too long:
$request->session()->put('my-sessions', [
'term' => $request->term,
'section' => $request->section,
]);
// Too long
$request->session()->get('my-sessions')['term'];
$request->session()->get('my-sessions')['section'];
I know foreach will do the job, but Is there more a "Laravel way" or built in function to do that ?
I’m using FileCache in my cache component. In my controller, I’m using :
[
'class' => 'yii\filters\HttpCache',
'only' => ['view'],
'etagSeed' => function ($action, $params) {
$model = $this->findModel(Yii::$app->request->get("id"));
return $model->update_time;
},
],
With etagSeed and/or lastModified I got the same behavior issue:
The cache works well with yii\filters\PageCache and yii\filters\HttpCache. But when the cache is invalidated (for example after updating the page), I still see the old cached content.
So when I'm visiting the target page from other page, I'm getting the old content. But when I push F5, the page refreshs with the last content.
I've checked the Etag value on my GET request in the browser, and I've found that I'm getting the old Etag value until I refresh the page using the F5 button.
This can be a standard browser behavior when using HttpCache ? But how can I see the new content without refreshing each time the browser to get the last content ?
Am I missing something ?
You could use PageCache and dependency in your controller. Note, that if your page is public, you should be prepared probably to accept an empty ID.
public function behaviors()
{
return [
'viewCache' => [
'class' => 'backend\components\filters\PageCache',
'only' => ['view'],
'duration' => 86400, // 1 day
'variations' => [
$_GET['id'] ?? null,
],
'dependency' => [
'class' => 'yii\caching\DbDependency',
'sql' => 'SELECT update_time FROM my_table WHERE id = :id',
'params' => [
':id' => $_GET['id'] ?? null,
]
]
'enabled' => [
isset($_GET['id']),
],
],
];
}
I got problem with Zend 2 session
When I 'quickly' double click 'Enter' in _POST form ( twice submit form before first respond) session is destroyed. When I submit 'in normal speed' all is OK.
My session configuration is exact copy of this http://framework.zend.com/manual/2.1/en/modules/zend.session.manager.html
only difference is
'session' => array(
'config' => array(
'class' => 'Zend\Session\Config\SessionConfig',
'options' => array(
'name' => 'myapp',
'remember_me_seconds' => 3600, //60 min session
'use_cookies' => true,
// 'cookie_httponly' => true, -> not working with Zfc-user subdomain
'cookie_domain'=>'domain.com',
),
),
'storage' => 'Zend\Session\Storage\SessionArrayStorage',
'validators' => array(
'Zend\Session\Validator\RemoteAddr',
'Zend\Session\Validator\HttpUserAgent',
),
),
In controler I have:
const NAMESPACE_REGORG = 'initialized';
protected $_sessionRegContainer;
public function packageAction() {
//check if user login and redirect
if ($this->zfcUserAuthentication()->hasIdentity()) {
//some staff here
}
//save value to session
$package = $this->getEvent()->getRouteMatch()->getParam('id');
$this->_sessionRegContainer = new Container(static::NAMESPACE_REGORG);
$this->_sessionRegContainer->package = $package;
return $this->redirect()->toRoute(static::ROUTE_LOGIN);
}
public function loginAction() {
//restore session
$this->_sessionRegContainer = new Container(static::NAMESPACE_REGORG);
//create form staff.. if submited by double click session is loosing
//value of $this->_sessionRegContainer->package
}
Page use Doctrine 2 ORM , Zfc-user module for authentication and sub-domain for all Zend 2 related content - main domain.com is static html.
It is worth to mention that when I use simple new Container() session with out all setup from Zend page - session work fine with 'double click' but zfc-user stop to work :(
Any idea why session is destroyed? Any help will be appreciated
I sorted it by removing
$session->start();
$session->rememberMe();
from Zend 2 exmple setup -> http://framework.zend.com/manual/2.1/en/modules/zend.session.manager.html
Double click session destroy ended (fixed).
ps. It look like they already remove rememberMe() from exmple.
Thanks for all help!