Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

error saving sessions #9438

Closed
spiritdead opened this issue Aug 16, 2015 · 67 comments · Fixed by #17188
Closed

error saving sessions #9438

spiritdead opened this issue Aug 16, 2015 · 67 comments · Fixed by #17188
Assignees
Milestone

Comments

@spiritdead
Copy link

hi all, im using the new version of the yii2 2.0.6 but i have this problem

i get this Error

[16-Aug-2015 19:18:46 UTC] PHP Fatal error: Uncaught exception 'yii\base\ErrorException' with message 'Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/tmp)' in Unknown:0
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleError(2, 'Unknown: Failed...', 'Unknown', 0, Array)
#1 {main}

thrown in Unknown on line 0

and is because i use this configuration

'session' => [
            'class' => 'yii\web\DbSession',
            'readCallback' => function ($fields) {
                    return [
                        'expireDate' => Yii::$app->formatter->asDate($fields['expire']),
                    ];
                },
            'writeCallback' => function ($session) {
                    return [
                        'user_id' => Yii::$app->user->id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'is_trusted' => $session->get('is_trusted', false),
                        'controllerCurrent' => Yii::$app->requestedAction->controller->id,
                        'actionCurrent' => Yii::$app->requestedAction->id,
                        'pageCurrent' => Yii::$app->id,
                        'is_guest' => Yii::$app->user->isGuest
                    ];
                }
        ]

in the common.php

in the localhost work Perfectly but in the remote i get the error

any have idea how can solve this ?

@cebe
Copy link
Member

cebe commented Aug 16, 2015

Please verify that the current setting of session.save_path is correct (/tmp)'

looks like a server configuration issue. Please make sure your server is configured correctly. If you still think there is a yii issue here, please give more details about where.

@cebe cebe closed this as completed Aug 16, 2015
@spiritdead
Copy link
Author

@cebe i know but why yii2 cant implement session_save_path('folder'); for this cases ? and define the config in the config.php ?

and yes is the server im trying contact the support

@cebe
Copy link
Member

cebe commented Aug 16, 2015

as far as I see you are using DbSession, so how is session_save_path involved here?

@spiritdead
Copy link
Author

'session' => [
            'class' => 'yii\web\DbSession',
            'readCallback' => function ($fields) {
                    return [
                        'expireDate' => Yii::$app->formatter->asDate($fields['expire']),
                    ];
                },
            'writeCallback' => function ($session) {
                    return [
                        'user_id' => Yii::$app->user->id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'is_trusted' => $session->get('is_trusted', false),
                        'controllerCurrent' => Yii::$app->requestedAction->controller->id,
                        'actionCurrent' => Yii::$app->requestedAction->id,
                        'pageCurrent' => Yii::$app->id,
                        'is_guest' => Yii::$app->user->isGuest
                    ];
                }
        ],

when i use write and read callbacks, this save the session file in the /temp and in my localhost work good, but in this remote i get the error and cant log-in, in this case is true i need call the datacenter, but if yii2 can provide the parameter for change this folder i think this will be a good solution

the session_save_path('folder'); is a method php for change the folder

@cebe cebe reopened this Aug 16, 2015
@cebe cebe added the status:to be verified Needs to be reproduced and validated. label Aug 16, 2015
@cebe cebe added this to the 2.0.x milestone Aug 16, 2015
@spiritdead
Copy link
Author

@cebe thx for open this, if can provide the option for define a custom path for save the session in the common\config.php etc a additional param like $sessionPath etc in the hosting is /home/user/temp/ and the php when you try get the path get /temp/ u.u and of course error

@cebe
Copy link
Member

cebe commented Aug 16, 2015

the actual issue here is, that the DbSession class should never try to store a session file somewhere on the disk. I reopened this primarily as a bug report.

@cebe cebe added the type:bug Bug label Aug 16, 2015
@spiritdead
Copy link
Author

that will be true :S i tryed too, change 2 time the path in the web/index.php

[16-Aug-2015 21:46:18 UTC] PHP Fatal error: Uncaught exception 'yii\base\ErrorException' with message 'Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/home/bluegerc/temp/)' in Unknown:0
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleError(2, 'Unknown: Failed...', 'Unknown', 0, Array)
#1 {main}
thrown in Unknown on line 0

[16-Aug-2015 21:47:40 UTC] PHP Fatal error: Uncaught exception 'yii\base\ErrorException' with message 'Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/home/bluegerc/public_html/temp/)' in Unknown:0
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleError(2, 'Unknown: Failed...', 'Unknown', 0, Array)
#1 {main}
thrown in Unknown on line 0

@spiritdead
Copy link
Author

@cebe a question i will need wait the 2.0.7 for use this ? :/

@cebe
Copy link
Member

cebe commented Aug 17, 2015

there is not even a fix for it so I can not tell you when it will be fixed.

@cebe cebe modified the milestones: 2.0.7, 2.0.x Aug 17, 2015
@cebe cebe self-assigned this Aug 17, 2015
@spiritdead
Copy link
Author

i think the problem is in the yii\web\session the base class of the dbsession

@spiritdead
Copy link
Author

@samdark i hosted this in a remote server, and in the logs i receive this error, and i cant login, when i comment the session configuration in the common config.php this work again.
Is true why dbsession write in the disk a file session? like this "sess_1isgea6dp79tn8e0vpi1o8m5h5" i can see this in my /tmp folder in XAMPP(localhost)

@fcaldarelli
Copy link
Member

I've solved putting

'is_guest' => (\Yii::$app->user->getIdentity(false) == null)

Otherwise calling \Yii::$app->user->isGuest I also get that error

@spiritdead
Copy link
Author

@FabrizioCaldarelli the problem is, this class create a file in the server, and in webservers i get errors :/

@fcaldarelli
Copy link
Member

fcaldarelli commented Nov 8, 2015

What class are you talking about?

I refer to this configuration:

'session' => [
            'class' => 'yii\web\DbSession',
            'readCallback' => function ($fields) {
                    return [
                        'expireDate' => Yii::$app->formatter->asDate($fields['expire']),
                    ];
                },
            'writeCallback' => function ($session) {
                    return [
                        'user_id' => Yii::$app->user->id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'is_trusted' => $session->get('is_trusted', false),
                        'controllerCurrent' => Yii::$app->requestedAction->controller->id,
                        'actionCurrent' => Yii::$app->requestedAction->id,
                        'pageCurrent' => Yii::$app->id,
                        'is_guest' => (\Yii::$app->user->getIdentity(false) == null)
                    ];
                }
        ]

@spiritdead
Copy link
Author

@FabrizioCaldarelli the class DbSessions
@cebe any have idea how fix this ?

@cebe cebe removed their assignment Dec 14, 2015
@andrewnester
Copy link
Contributor

Hi @spiritdead
Could you please provide all content of your config file?
I am trying to reproduce your error

@spiritdead
Copy link
Author

@andrewnester yeah is this

<?php

return [
    'language' => 'es-ES',
    'name' => 'Proyect Cat',
    'timeZone' => 'Europe/Berlin',
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'modules' => [
        'gridview' => [
            'class' => '\kartik\grid\Module'
        ]
    ],
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'slimApi' =>[
            'class' => 'common\components\SlimApi',
            'apiKey' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            'userID' => 'xxxx'
        ],
        'session' => [
            'class' => 'yii\web\DbSession',
            'readCallback' => function ($fields) {
                    return [
                        'expireDate' => Yii::$app->formatter->asDate($fields['expire']),
                    ];
                },
            'writeCallback' => function ($session) {
                    return [
                        'user_id' => Yii::$app->user->id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'is_trusted' => $session->get('is_trusted', false),
                        'controllerCurrent' => Yii::$app->requestedAction->controller->id,
                        'actionCurrent' => Yii::$app->requestedAction->id,
                        'pageCurrent' => Yii::$app->id,
                        'is_guest' => Yii::$app->user->isGuest
                    ];
                }
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
                'db'=>[
                    'class' => 'yii\log\DbTarget',
                    'levels' => ['error', 'warning'],
                    'except'=>['yii\web\HttpException', 'yii\i18n\I18N'],
                    'prefix'=>function(){
                            $url = !Yii::$app->request->isConsoleRequest ? Yii::$app->request->getUrl() : null;
                            $user = Yii::$app->has('user', true) ? Yii::$app->user : null;
                            $userName = $user ? $user->identity->username : '-';
                            return sprintf('[%s][%s][%s]',$userName, Yii::$app->id, $url);
                        },
                    'logVars'=>[],
                    'logTable'=>'log'
                ]
            ],
        ],
        'urlManager'=>[
            //'urlFormat'=>'path',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules'=>[
                '<controller:[a-z\-]+>/<id:\d+>'=>'<controller>/view',
                '<controller:[a-z\-]+>/<action:[a-z\-]+>/<id:\d+>'=>'<controller>/<action>',
                '<controller:[a-z\-]+>/<action:[a-z\-]+>'=>'<controller>/<action>',
            ],
        ],
        'urlManagerUpload' => [
            'class' => 'yii\web\urlManager',
            'baseUrl' => '/uploads/',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
        ],
        'urlManagerBase' => [
            'class' => 'yii\web\urlManager',
            'baseUrl' => '/',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
        ],
        'urlManagerFrontToBack' => [
            'class' => 'yii\web\urlManager',
            'baseUrl' => '/backend',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
        ],
        'urlManagerBackToFront' => [
            'class' => 'yii\web\urlManager',
            'baseUrl' => '/frontend',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
        ]
    ],
];

@andrewnester
Copy link
Contributor

Can't reproduce it.
@FabrizioCaldarelli @spiritdead guys, could you please provide details how are you reproducing this error?

@spiritdead
Copy link
Author

@andrewnester is in shared servers, in the localhost work good, but the problem is, if i use dbsession why this write a file in the temp (session file) ?

@andrewnester
Copy link
Contributor

@spiritdead are you sure you have session table in your database on your hosted server? and could you please attach your Yii log file, it will help to find out what's wrong, because I can reproduce error neither on localhost or on hosted server.

@spiritdead
Copy link
Author

@andrewnester i added the migration of the table session of course, but this report is a little old and i use now other server :/

@ghost
Copy link

ghost commented Sep 4, 2017

I I've solved this problem by overriding close() method in a subclass of DbSession like this:
public function close(){}
but I don't know have any side effect or not.

@samdark
Copy link
Member

samdark commented Sep 5, 2017

@mhd-shf is your session properly written with empty close()?

@ghost
Copy link

ghost commented Sep 5, 2017

@samdark Yes, I have no problem with that. maybe this is specific to my project that every thing is ok.

@alexxxst
Copy link

alexxxst commented Sep 8, 2017

public function close(){}

doesn't work. But I have full log now.
DbSession.zip

@samdark
Copy link
Member

samdark commented Sep 9, 2017

Thanks for logs. It's, indeed #9438 (comment)

@degibons
Copy link

I have the same problem with messages in my nginx error log:

2017/11/13 18:03:23 [error] 11037#11037: *49685041 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught yii\base\ErrorException: Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/var/lib/php/sessions) in Unknown:0
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleError(2, 'Unknown: Failed...', 'Unknown', 0, NULL)
#1 {main}

app config has the following:

'session' => [
            'class' => 'yii\web\DbSession',
            'sessionTable' => 'user_http_session',
            'writeCallback' => function ($session) {
                return [
                    'userId' => Yii::$app->getUser()->getId(),
                ];
            },
            'name' => 'sid', 
            'timeout' => 7200, 
        ],

Php version 7.0.8, Yii 2.0.13
Php session info:
screenshot--2017-11-13-18-13-23

Does anyone know how to fix it?

@samdark
Copy link
Member

samdark commented Nov 13, 2017

Yes.

 'userId' => Yii::$app->getUser() ? Yii::$app->getUser()->getId() : null, // or if you have not null, use an empty string or 0

@degibons
Copy link

Unfortunally it's still there:

2017/11/13 18:30:28 [error] 11038#11038: *49722401 FastCGI sent in stderr: "PHP message: PHP Fatal error: Uncaught yii\base\ErrorException: Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/var/lib/php/sessions) in Unknown:0
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleError(2, 'Unknown: Failed...', 'Unknown', 0, NULL)
#1 {main}
thrown in Unknown on line 0" while reading upstream, client: 37.215.14.236, server: www.xxx.xxx, request: "POST /xxx/xxx HTTP/1.1", upstream: "fastcgi://unix:/var/run/php/php7.0-fpm-ne-pool.sock:", host: "www.xxx.xxx", referrer: "https://www.xxx.xxx/xxx/xxx"

@samdark
Copy link
Member

samdark commented Nov 13, 2017

What if you'll comment out writeCallback? Same issue or not?

@degibons
Copy link

degibons commented Nov 13, 2017

no, no errors. Then I comment writeCallback no errors appears.

@alexxxst
Copy link

alexxxst commented Nov 13, 2017

[13-Nov-2017 18:32:33 Europe/Moscow] PHP Fatal error:  Uncaught yii\base\ErrorException: Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown:0
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleError(2, 'Unknown: Failed...', 'Unknown', 0, NULL)
#1 {main}
  thrown in Unknown on line 0

Have the same.

And my new friend after 2.0.13:

2017-11-11 12:29:01 [79.134.*.*][252][smr1d7k73i5pn9rntljrqtosu2][info][application] $_GET = [
    'q' => '/option/get'
]
2017-11-11 12:29:02 [79.134.*.*][252][smr1d7k73i5pn9rntljrqtosu2][error][yii\db\IntegrityException] PDOException: SQLSTATE[23000]: Integrity constraint viol
ation: 1062 Duplicate entry 'smr1d7k73i5pn9rntljrqtosu2' for key 'PRIMARY' in /var/www/basic/vendor/yiisoft/yii2/db/Command.php:994
Stack trace:
#0 /var/www/basic/vendor/yiisoft/yii2/db/Command.php(994): PDOStatement->execute()
#1 /var/www/basic/vendor/yiisoft/yii2/web/DbSession.php(179): yii\db\Command->execute()
#2 [internal function]: yii\web\DbSession->writeSession('smr1d7k73i5pn9r...', '__flash|a:0:{}')
#3 /var/www/basic/vendor/yiisoft/yii2/web/Session.php(295): session_regenerate_id(false)
#4 /var/www/basic/vendor/yiisoft/yii2/web/DbSession.php(103): yii\web\Session->regenerateID(false)
#5 /var/www/basic/vendor/yiisoft/yii2/web/User.php(624): yii\web\DbSession->regenerateID(true)
#6 /var/www/basic/vendor/yiisoft/yii2/web/User.php(292): yii\web\User->switchIdentity(Object(app\models\User), 2592000)
#7 /var/www/basic/vendor/yiisoft/yii2/web/User.php(680): yii\web\User->loginByCookie()
#8 /var/www/basic/vendor/yiisoft/yii2/web/User.php(188): yii\web\User->renewAuthStatus()
#9 /var/www/basic/vendor/yiisoft/yii2/web/User.php(333): yii\web\User->getIdentity()
#10 /var/www/basic/vendor/yiisoft/yii2/base/Component.php(133): yii\web\User->getIsGuest()
#11 /var/www/basic/vendor/yiisoft/yii2-debug/panels/UserPanel.php(75): yii\base\Component->__get('isGuest')
#12 /var/www/basic/vendor/yiisoft/yii2/base/BaseObject.php(108): yii\debug\panels\UserPanel->init()
#13 [internal function]: yii\base\BaseObject->__construct(Array)
#14 /var/www/basic/vendor/yiisoft/yii2/di/Container.php(381): ReflectionClass->newInstanceArgs(Array)
#15 /var/www/basic/vendor/yiisoft/yii2/di/Container.php(156): yii\di\Container->build('yii\\debug\\panel...', Array, Array)
#16 /var/www/basic/vendor/yiisoft/yii2/BaseYii.php(349): yii\di\Container->get('yii\\debug\\panel...', Array, Array)
#17 /var/www/basic/vendor/yiisoft/yii2-debug/Module.php(177): yii\BaseYii::createObject(Array)
#18 /var/www/basic/vendor/yiisoft/yii2-debug/Module.php(149): yii\debug\Module->initPanels()
#19 /var/www/basic/vendor/yiisoft/yii2/base/BaseObject.php(108): yii\debug\Module->init()
#20 /var/www/basic/vendor/yiisoft/yii2/base/Module.php(158): yii\base\BaseObject->__construct(Array)
#21 [internal function]: yii\base\Module->__construct('debug', Object(yii\web\Application), Array)
#22 /var/www/basic/vendor/yiisoft/yii2/di/Container.php(381): ReflectionClass->newInstanceArgs(Array)
#23 /var/www/basic/vendor/yiisoft/yii2/di/Container.php(156): yii\di\Container->build('yii\\debug\\Modul...', Array, Array)
#24 /var/www/basic/vendor/yiisoft/yii2/BaseYii.php(349): yii\di\Container->get('yii\\debug\\Modul...', Array, Array)
#25 /var/www/basic/vendor/yiisoft/yii2/base/Module.php(427): yii\BaseYii::createObject(Array, Array)
#26 /var/www/basic/vendor/yiisoft/yii2/base/Application.php(315): yii\base\Module->getModule('debug')
#27 /var/www/basic/vendor/yiisoft/yii2/web/Application.php(69): yii\base\Application->bootstrap()
#28 /var/www/basic/vendor/yiisoft/yii2/base/Application.php(273): yii\web\Application->bootstrap()
#29 /var/www/basic/vendor/yiisoft/yii2/base/BaseObject.php(108): yii\base\Application->init()
#30 /var/www/basic/vendor/yiisoft/yii2/base/Application.php(206): yii\base\BaseObject->__construct(Array)
#31 /var/www/panel3/panel/web/index.php(25): yii\base\Application->__construct('[<span class="s...')
#32 {main}

Next yii\db\IntegrityException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'smr1d7k73i5pn9rntljrqtosu2' for key 'PRIMARY'
The SQL being executed was: INSERT INTO `session` (`data`, `user_id`, `id`, `expire`) VALUES ('__flash|a:0:{}', 252, 'smr1d7k73i5pn9rntljrqtosu2', 1510396142) i
n /var/www/basic/vendor/yiisoft/yii2/db/Schema.php:595
Stack trace:
#0 /var/www/basic/vendor/yiisoft/yii2/db/Command.php(1004): yii\db\Schema->convertException(Object(PDOException), 'INSERT INTO `se...')
#1 /var/www/basic/vendor/yiisoft/yii2/web/DbSession.php(179): yii\db\Command->execute()
#2 [internal function]: yii\web\DbSession->writeSession('smr1d7k73i5pn9r...', '__flash|a:0:{}')
#3 /var/www/basic/vendor/yiisoft/yii2/web/Session.php(295): session_regenerate_id(false)
#4 /var/www/basic/vendor/yiisoft/yii2/web/DbSession.php(103): yii\web\Session->regenerateID(false)
#5 /var/www/basic/vendor/yiisoft/yii2/web/User.php(624): yii\web\DbSession->regenerateID(true)
#6 /var/www/basic/vendor/yiisoft/yii2/web/User.php(292): yii\web\User->switchIdentity(Object(app\models\User), 2592000)
#7 /var/www/basic/vendor/yiisoft/yii2/web/User.php(680): yii\web\User->loginByCookie()
#8 /var/www/basic/vendor/yiisoft/yii2/web/User.php(188): yii\web\User->renewAuthStatus()
#9 /var/www/basic/vendor/yiisoft/yii2/web/User.php(333): yii\web\User->getIdentity()
#10 /var/www/basic/vendor/yiisoft/yii2/base/Component.php(133): yii\web\User->getIsGuest()
#11 /var/www/basic/vendor/yiisoft/yii2-debug/panels/UserPanel.php(75): yii\base\Component->__get('isGuest')
#12 /var/www/basic/vendor/yiisoft/yii2/base/BaseObject.php(108): yii\debug\panels\UserPanel->init()
#13 [internal function]: yii\base\BaseObject->__construct(Array)
#14 /var/www/basic/vendor/yiisoft/yii2/di/Container.php(381): ReflectionClass->newInstanceArgs(Array)
#15 /var/www/basic/vendor/yiisoft/yii2/di/Container.php(156): yii\di\Container->build('yii\\debug\\panel...', Array, Array)
#16 /var/www/basic/vendor/yiisoft/yii2/BaseYii.php(349): yii\di\Container->get('yii\\debug\\panel...', Array, Array)
#17 /var/www/basic/vendor/yiisoft/yii2-debug/Module.php(177): yii\BaseYii::createObject(Array)
#18 /var/www/basic/vendor/yiisoft/yii2-debug/Module.php(149): yii\debug\Module->initPanels()
#19 /var/www/basic/vendor/yiisoft/yii2/base/BaseObject.php(108): yii\debug\Module->init()
#20 /var/www/basic/vendor/yiisoft/yii2/base/Module.php(158): yii\base\BaseObject->__construct(Array)
#21 [internal function]: yii\base\Module->__construct('debug', Object(yii\web\Application), Array)
#22 /var/www/basic/vendor/yiisoft/yii2/di/Container.php(381): ReflectionClass->newInstanceArgs(Array)
#23 /var/www/basic/vendor/yiisoft/yii2/di/Container.php(156): yii\di\Container->build('yii\\debug\\Modul...', Array, Array)
#24 /var/www/basic/vendor/yiisoft/yii2/BaseYii.php(349): yii\di\Container->get('yii\\debug\\Modul...', Array, Array)
#25 /var/www/basic/vendor/yiisoft/yii2/base/Module.php(427): yii\BaseYii::createObject(Array, Array)
#26 /var/www/basic/vendor/yiisoft/yii2/base/Application.php(315): yii\base\Module->getModule('debug')
#27 /var/www/basic/vendor/yiisoft/yii2/web/Application.php(69): yii\base\Application->bootstrap()
#28 /var/www/basic/vendor/yiisoft/yii2/base/Application.php(273): yii\web\Application->bootstrap()
#29 /var/www/basic/vendor/yiisoft/yii2/base/BaseObject.php(108): yii\base\Application->init()
#30 /var/www/basic/vendor/yiisoft/yii2/base/Application.php(206): yii\base\BaseObject->__construct(Array)
#31 /var/www/panel3/panel/web/index.php(25): yii\base\Application->__construct('[<span class="s...')
#32 {main}
Additional Information:
Array
(
    [0] => 23000
    [1] => 1062
    [2] => Duplicate entry 'smr1d7k73i5pn9rntljrqtosu2' for key 'PRIMARY'
)

With callback like this:

'writeCallback' => function () { 
               if (Yii::$app->has('user') && !Yii::$app->get('user')->getIsGuest())
                    return ['user_id' => Yii::$app->get('user')->getIdentity()->user_id];
            },

@degibons
Copy link

Also I have this #13212 issue too. Do you think it may be connected?
Just for a note. I recently upgraded my project from Yii1. In the previous version the same functionality worked without errors (with the same server environments).

@samdark
Copy link
Member

samdark commented Nov 13, 2017

Duplicate entry is #13212. writeCallback one is weird. Yii1 was hiding the issue same as Yii 2.0.12.

@degibons
Copy link

So, what's the problem with this issue (error saving sassions with writeCallback) and how to fix it is unclear, right?

@samdark
Copy link
Member

samdark commented Nov 16, 2017

Yes. It's totally mysterious.

@lubosdz
Copy link
Contributor

lubosdz commented Mar 5, 2019

I stumbled upon this error too when using DB session storage and here's what I found:

  • it only occurs when using custom DB session handler (mysql/mariadb in my case) AND when trying to read anything from the session in one of custom session field (commonly Yii::$user->id)
  • the reason seems to be wrong workflow when closing the session. The session is first closed in session->close() and after session_write_close() it jumps to DbSession::writeSession(). If a custom field is user ID, this needs to be read from the session, which is already closed (inactive after session_write_close()). So framework attempts to re-open it (second time during a single request) inside function User::renewAuthStatus() in order to read user ID (or anything from session would do the same).

The error should be reproducible by clicking on captcha image and configured writeCallback custom fields e.g.

'session' => [
	'class' => 'yii\web\DbSession',
	'sessionTable' => 'sys_session',
	'writeCallback' => function($session){
		$uid = 0;
		if($user = Yii::$app->user){
			$uid = (int) $user->getId(); // <-- session already closed, will re-open & re-close
		}
		return [
			'id_user' => $uid,
			'last_write' => date('Y-m-d H:i:s'),
		];
	}
],

The issue could be solved preparing session custom fields before closing the session (before executing session_write_close()).

@samdark
Copy link
Member

samdark commented Mar 5, 2019

@lubosdz am I correct that it's a custom write callback issue rather than framework issue?

@lubosdz
Copy link
Contributor

lubosdz commented Mar 5, 2019

@samdark No, I believe it's a framework issue - wrong workflow when closing the database session. Custom database session fields should be populated earlier than the session is closed.

@samdark
Copy link
Member

samdark commented Mar 5, 2019

@lubosdz since you're on it, can you handle a pull request?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.