Yii2: error saving sessions

Created on 16 Aug 2015  路  67Comments  路  Source: yiisoft/yii2

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 ?

php7 bug

All 67 comments

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 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

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

'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 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

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.

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

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

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

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

@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)

I've solved putting

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

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

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

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)
                    ];
                }
        ]

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

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

@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,
        ]
    ],
];

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

@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) ?

@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.

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

I was having this same error too for the longest time and couldn't figure out why. After spending hours tracing the code with the debugger I discovered the problem for me was in my writeCallback() function, like you inside that function I had several calls to $session->get('param_name').

The problem is, the writeCallback function is called upon sessionClose(), and by the time it gets to my call to session->get() the session is already closed. Inside the session->get() function the first thing it does is open the session if it is not already open, so my session was getting reopened after it had been closed. Then when the script ends and the memory is freed up from my session object, session_destroy() is called and that's when the error is triggered: "'Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/tmp)'", I believe because the session was still open?

See if commenting out your line:
'is_trusted' => $session->get('is_trusted', false),

fixes your problem. I had to rework my read and write callback functions and once I eliminated the session->get calls everything worked OK. I don't know if this is a bug or if its a result of me using the session class incorrectly, but I had to store the session params I needed in separate variables in memory and access them there in order to get the writeCallback to work. Maybe not the ideal solution but at least now it works. Hope it helps you.

@joetwostep @samdark that will be true, but then we got to the session variable in the function ?

if we get this error getting a property of the session, why receive this var in the parameters of the function...

'writeCallback' => function ($session) {

we should receive variable from a secondary memory location that does not affect the session in general not?

secondary memory location?

if this is the problem

The problem is, the writeCallback function is called upon sessionClose(), and by the time it gets to my call to session->get() the session is already closed. Inside the session->get() function the first thing it does is open the session if it is not already open, so my session was getting reopened after it had been closed. Then when the script ends and the memory is freed up from my session object, session_destroy() is called and that's when the error is triggered: "'Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/tmp)'", I believe because the session was still open?

why the writecallback give access to the parameter $session ?

@joetwostep are you sure session_write_close() calls write callback with session already closed? Which PHP version are you using?

Normally it should be write and then close.

Have same issue:

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

Any ideas (fixes)?

'class' => 'yii\web\DbSession',

@klimov-paul it should not even try to write to a file.

This error happens when the writeCallback is trying to access something that has not been created yet. Such as the Yii::$app->user. This normally happens because of an uncaught error that causes the app to error out before the accessed object is setup.

To reproduce the error, set write callback to:

'writeCallback' => function($session) { return [ 'user_id' => \Yii::$app->user->id ]; }

And create a controller action that executes the following:
ArrayHelper('string',null,[]);

Verified.

I have no idea how to prevent this error. @samdark do you?

No immediate idea. Need to dig into it more.

Any news here?

Not yet. Do you have additional info that may help solving it?

Nothing but tracelog.

yii\base\ErrorException: session_regenerate_id(): Session write failed. ID: user (path: /var/lib/php/session) in /var/www/basic/vendor/yiisoft/yii2/web/Session.php:295
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleError(2, 'session_regener...', '/var/www/basic/...', 295, Array)
#1 /var/www/basic/vendor/yiisoft/yii2/web/Session.php(295): session_regenerate_id(false)
#2 /var/www/basic/vendor/yiisoft/yii2/web/DbSession.php(103): yii\web\Session->regenerateID(false)
#3 /var/www/basic/vendor/yiisoft/yii2/web/User.php(618): yii\web\DbSession->regenerateID(true)
#4 /var/www/basic/vendor/yiisoft/yii2/web/User.php(292): yii\web\User->switchIdentity(Object(app\models\User), 2592000)
#5 /var/www/basic/vendor/yiisoft/yii2/web/User.php(674): yii\web\User->loginByCookie()
#6 /var/www/basic/vendor/yiisoft/yii2/web/User.php(188): yii\web\User->renewAuthStatus()
#7 /var/www/basic/vendor/yiisoft/yii2/web/User.php(333): yii\web\User->getIdentity()
#8 /var/www/basic/vendor/yiisoft/yii2/base/Component.php(132): yii\web\User->getIsGuest()
#9 /var/www/panel3/panel/controllers/UserController.php(67): yii\base\Component->__get('isGuest')
#10 /var/www/basic/vendor/yiisoft/yii2/base/Controller.php(154): app\controllers\UserController->beforeAction(Object(yii\base\InlineAction))
#11 /var/www/basic/vendor/yiisoft/yii2/base/Module.php(523): yii\base\Controller->runAction('login', Array)
#12 /var/www/basic/vendor/yiisoft/yii2/web/Application.php(102): yii\base\Module->runAction('user/login', Array)
#13 /var/www/basic/vendor/yiisoft/yii2/base/Application.php(380): yii\web\Application->handleRequest(Object(yii\web\Request))
#14 /var/www/panel3/panel/web/index.php(22): yii\base\Application->run()
#15 {main}

Nothing but tracelog.

I would not call that nothing, there is a lot of useful information in here.

DbSession is calling session_regenerate_id() which is then trying to write files for whatever reason.

@alexxxst could you provide your PHP config regarding sessions, i.e. all settings that begin with session. and the PHP version you are using?

There are nothing specific.

bash-4.1$ php -i | grep session
igbinary session support => yes
session
session.auto_start => Off => Off
session.cache_expire => 180 => 180
session.cache_limiter => nocache => nocache
session.cookie_domain => no value => no value
session.cookie_httponly => Off => Off
session.cookie_lifetime => 0 => 0
session.cookie_path => / => /
session.cookie_secure => Off => Off
session.entropy_file => /dev/urandom => /dev/urandom
session.entropy_length => 32 => 32
session.gc_divisor => 1000 => 1000
session.gc_maxlifetime => 3600 => 3600
session.gc_probability => 1 => 1
session.hash_bits_per_character => 5 => 5
session.hash_function => 0 => 0
session.lazy_write => On => On
session.name => PHPSESSID => PHPSESSID
session.referer_check => no value => no value
session.save_handler => files => files
session.save_path => /var/lib/php/session => /var/lib/php/session
session.serialize_handler => php => php
session.upload_progress.cleanup => On => On
session.upload_progress.enabled => On => On
session.upload_progress.freq => 1% => 1%
session.upload_progress.min_freq => 1 => 1
session.upload_progress.name => PHP_SESSION_UPLOAD_PROGRESS => PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix => upload_progress_ => upload_progress_
session.use_cookies => On => On
session.use_only_cookies => On => On
session.use_strict_mode => Off => Off
session.use_trans_sid => 0 => 0
bash-4.1$ php -v
PHP 7.0.20 (cli) (built: Jun 13 2017 19:33:52) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
    with Zend OPcache v7.0.20, Copyright (c) 1999-2017, by Zend Technologies
bash-4.1$ ./yii help
This is Yii version 2.0.12.

are you sure the webserver config is the same?

Yep, it's the same. Except session.save_handler of course. It is set to "user".

So to reproduce it in basic app. Session component config:

'session' => [
    'class' => 'yii\web\DbSession',
    'writeCallback' => function ($session) {
        return 1; // will cause fail 
    }
],

Then create session table as usual. Then modify your php.ini so default handler errors i.e. add something like session.save_path = "N;/non_existing".

After that login as admin and log out.

This is PHP 7 only issue. 5.6 works fine.

The error displayed is clear and is pointing to writeCallback if using 5.6 but is quite cryptic when using PHP 7. The fix could be made to DbSession::writeSession() so PHP 7 displays error correctly in debug mode:

} catch (\Exception $e) {
    $exception = ErrorHandler::convertExceptionToString($e);
    // its too late to use Yii logging here
    error_log($exception);
    if (YII_DEBUG) {
        Yii::$app->errorHandler->handleException($e); // <----- this
    }

     return false;
}

@alexxxst do you have writeCallback? Do you have anything in PHP logs (not Yii log but PHP one)?

Yep, writeCallback returns array with user_id. But nothing special in PHP logs.

Looks like the case I've described in https://github.com/yiisoft/yii2/issues/9438#issuecomment-326141935 Do you have a chance to try the change I've proposed?

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.

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

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

public function close(){}

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

Thanks for logs. It's, indeed https://github.com/yiisoft/yii2/issues/9438#issuecomment-326141935

Related:

  • #1946
  • #2916
  • #9212
  • #11726

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?

Yes.

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

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"

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

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

[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];
            },

Also I have this https://github.com/yiisoft/yii2/issues/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).

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

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

Yes. It's totally mysterious.

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()).

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

@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.

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Mirocow picture Mirocow  路  56Comments

samdark picture samdark  路  63Comments

vercotux picture vercotux  路  47Comments

dhiman252 picture dhiman252  路  44Comments

schmunk42 picture schmunk42  路  47Comments