Database sessions are not stored in DB

198 views
Skip to first unread message

Thomas Preissler

unread,
Apr 27, 2016, 5:09:49 PM4/27/16
to Fat-Free Framework
HI,

I was using PHP file based sessions on a Debian server, which stores the session information in /var/lib/php5, I believe.
I would like to store my sessions in the DB (MariaDB) I am already using for my webapp. So I am using the following
code at the end of index.php:

new \DB\SQL\Session($f3->get('DB'), 'session', FALSE, function($session) {
   
//suspect session
    $logger
= new \Log('tmp/ssession.log');
    $f3
=\Base::instance();
   
if (($ip=$session->ip())!=$f3->get('IP'))
        $logger
->write('user changed IP:'.$ip);
   
else
        $logger
->write('user changed browser/device:'.$f3->get('AGENT'));

   
// The default behaviour destroys the supicious session
   
return false;
});

$f3
->run();



And tmp/ssession.log is empty - but there are other files there, .php files.
$f3->get('DB') is set correctly, my "session" table looks like this - auto created by F3:

MariaDB [XXX]> describe session;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| session_id | varchar(40)  | NO   | PRI | NULL    |       |
| data       | text         | YES  |     | NULL    |       |
| csrf       | text         | YES  |     | NULL    |       |
| ip         | varchar(40)  | YES  |     | NULL    |       |
| agent      | varchar(255) | YES  |     | NULL    |       |
| stamp      | int(11)      | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+

But as soon I logout, log back in nothing gets created in there, the # of records is 0.

What am I missing? It seems it insisting on file based sessions - CACHE is not set, could that be the reason?


Regards

Thomas

xfra35

unread,
Apr 30, 2016, 4:07:02 PM4/30/16
to Fat-Free Framework
Hi Thomas,

What's the issue exactly? I don't understand that sentence: "But as soon I logout, log back in nothing gets created in there, the # of records is 0."

Do you mean that the "session" table is empty?

Maybe try it simple first: new \DB\SQL\Session($f3->get('DB'),'session') and see if it works.

Thomas Preissler

unread,
May 1, 2016, 1:00:55 PM5/1/16
to Fat-Free Framework
Hi xfra35,

yes, that's the problem. No sessions are stored in my "session" table.
I am calling it exactly that way now and there is also a hive key DB as well.
                                                                                                                                                                                               
Yesterday I even added logger->write statements into the \DB\SQL\Session
constructor. It is indeed executed. But it doesn't store anything.
It looks like the session handler is overwritten again, but I have checked,
the "new Session()" is not anywhere.

Immediately after "new \DB\SQL\Session" I am setting SESSION.test and I
have debug statements in \DB\SQL\Session->write(),  My debug statements in write() are not
executed.

I even removed all "clear("SESSION")". No avail.

In regards to db access I am on MySQL  and even use root temporarily (on
dev, not on live). When I drop the session table it gets created again as
"session". I also tried it with the default "sessions", same thing.


Cheers

Thomas

xfra35

unread,
May 1, 2016, 6:12:19 PM5/1/16
to Fat-Free Framework
I have debug statements in \DB\SQL\Session->write()

What kind of debug statements? They should be written to disk (logger->write) not to screen, because the write() method is usually executed at script shutdown, when output is closed.

Also you can try to write to disk before shutdown, by calling session_write_close():

$f3->set('SESSION.test','123');
session_write_close(); // triggers write() and close()
echo $f3->get('SESSION.test'); // triggers open() and read()

If the problem persists with session_write_close(), that would mean it is not related to the shutdown sequence.

Thomas Preissler

unread,
May 2, 2016, 9:06:01 AM5/2/16
to Fat-Free Framework
I am using

$logger = new \Log('tmp/sessiondebug.log');-
$logger->write('session');-
$logger->write('table: ' . $table);

and that file gets created and there are log entries in there.

I tried now

new \DB\SQL\Session($f3->get('DB'), 'session');

$f3->set('SESSION.test','123');
session_write_close(); // triggers write() and close()
echo $f3->get('SESSION.test'); // triggers open() and read()

and then logging into my webapp, then checking the DB gives me

MariaDB [database]> select * from session;
Empty set (0.00 sec)

I am at loss here, I have no idea where else to look, why this is not working.
I also have a $logger = new \Log('tmp/sessiondebug.log'); $logger->write('sessiion write'); in DB\SQL\Session->write() and
that doesn't turn up in the debug file at all.

I am on PHP 7.0.6 with FPM and NginX.

Thomas Preissler

unread,
May 2, 2016, 10:01:47 AM5/2/16
to Fat-Free Framework
I did now this in \DB\SQL\Session->__construct:

                $done = session_set_save_handler(
                        array($this,'open'),
                        array($this,'close'),
                        array($this,'read'),
                        array($this,'write'),
                        array($this,'destroy'),
                        array($this,'cleanup')
        );
        if ($done) {
            $logger->write('handler_result true:', $done);
        } else {
            $logger->write('handler_result false:', $done);
        }

And my log shows me

 [127.0.0.1] handler_result false:

Any ideas?

Thomas Preissler

unread,
May 2, 2016, 10:29:03 AM5/2/16
to Fat-Free Framework
I just checked

php.ini:session.auto_start = 0

and I get the same from a phpinfo() loaded in the same directory.

xfra35

unread,
May 2, 2016, 11:46:12 AM5/2/16
to Fat-Free Framework
Oh nice catch. So the session handler is rejected for some reason.

Can you dump all session-related ini settings?

print_r(ini_get_all('session',FALSE)) should be enough.

Thomas Preissler

unread,
May 2, 2016, 1:40:06 PM5/2/16
to Fat-Free Framework
Array ( [session.auto_start] => 0 [session.cache_expire] => 180 [session.cache_limiter] => nocache [session.cookie_domain] => [session.cookie_httponly] => [session.cookie_lifetime] => 0 [session.cookie_path] => / [session.cookie_secure] => [session.entropy_file] => /dev/urandom [session.entropy_length] => 32 [session.gc_divisor] => 1000 [session.gc_maxlifetime] => 1440 [session.gc_probability] => 1 [session.hash_bits_per_character] => 5 [session.hash_function] => 0 [session.lazy_write] => 1 [session.name] => PHPSESSID [session.referer_check] => [session.save_handler] => files [session.save_path] => /tmp [session.serialize_handler] => php [session.upload_progress.cleanup] => 1 [session.upload_progress.enabled] => 1 [session.upload_progress.freq] => 1% [session.upload_progress.min_freq] => 1 [session.upload_progress.name] => PHP_SESSION_UPLOAD_PROGRESS [session.upload_progress.prefix] => upload_progress_ [session.use_cookies] => 1 [session.use_only_cookies] => 1 [session.use_strict_mode] => 0 [session.use_trans_sid] => 0 )

xfra35

unread,
May 2, 2016, 3:06:18 PM5/2/16
to Fat-Free Framework
Ok so everything looks ok. There's that session.entropy_length which is > 0 and that session.lazy_write = 1 but since the failure occurs during session_set_save_handler, that's probably not related.

If we look at the PHP source code, we see that the function returns FALSE if one of the two conditions occurs:
  • the session has already been started => a call to session_status() should clarify if that's the case
  • one of the provided functions is not a valid callback => that should not be the case, but you can easily check the server log and see if there's a message saying so
Also the function could return NULL, but I don't understand when. => you can also check if the returned value is FALSE or NULL.

Thomas Preissler

unread,
May 2, 2016, 3:23:22 PM5/2/16
to Fat-Free Framework
Ok, this is getting somewhere.

I added some session_start(); on various places in my index.php and it is always 1, yes!
Even just at the beginning, immediately after the <?php it is 1 as well.
And "sssh" does indeed return false, not NULL.

I don't have any prepend files or any other includes anywhere, but why on earth is the session already created?
My NginX config also doesn't do any thing fancy, basically just a

if (!-e $request)
rewrite ^(.*)$ /XXXX/index.php

and nothing else.

Just more puzzled.

xfra35

unread,
May 2, 2016, 4:47:38 PM5/2/16
to f3-fra...@googlegroups.com
I added some session_start()
Do you mean "session_status()"?

If yes, 1 means PHP_SESSION_NONE, so nothing wrong here.

Then we're left with case n°2:
  • one of the provided functions is not a valid callback => that should not be the case, but you can easily check the server log and see if there's a message saying so
What does the error log file say?

Thomas Preissler

unread,
May 2, 2016, 5:36:34 PM5/2/16
to Fat-Free Framework
I did use by mistake session_start, but I have tried the same thing again with session_status() [...]
and was able to narrow it down:

$f3->set('FLASH', Flash::instance());

(Taken from fabulog.)

*Before* this line session_status = 1, *After* this line session_status = 2;

I commented this out (temporarily) and ... now DB sessions are stored just fine.
I guess I just have to move this *after* creating my session.


Many, many thanks xfra35 for your time in troubleshooting this.

xfra35

unread,
May 2, 2016, 5:48:20 PM5/2/16
to Fat-Free Framework
You need indeed to register the SQL session handler as early as possible, before any session_start.

Glad to know you finally fixed it!
Reply all
Reply to author
Forward
0 new messages