1

Hello i'm trying to understand how sessions work and how does session_set_handler() works, so i've started build a class for session handling but i've encountered some problems with the write() function can you please help me solve the problem?

<?php
class Session extends Model
{
    public
        $connectionName = 'sessions',
        $sessionsId,
        $sessionsData;

    public function __construct()
    {
        parent::__construct();
        session_set_save_handler(
            array($this, 'Open'),
            array($this, 'Close'),
            array($this, 'Read'),
            array($this, 'Write'),
            array($this, 'Destroy'),
            array($this, 'Gc'));
        session_start();
    }

    public function __destruct()
    {
        session_write_close();
    }

    public function Open()
    {
        return true;
    }

    public function Close()
    {
        return true;
    }

    public function Read($sessionsId)
    {
        $this->stmt = $this->prepare("SELECT * FROM `sessions` WHERE `id` = :sessionId");
        $this->stmt->bindParam(":sessionId", $sessionsId);
        $this->stmt->execute();
        return $this->stmt->fetchAll();
    }

    public function Write($sessionsId, $sessionsData)
    {
        $this->stmt = $this->prepare("REPLACE INTO `sessions`.`sessions` 
        (`id`, `access`, `data`) 
        VALUES 
        (:sessionId, NOW(), :sessionValue)");
        $this->stmt->bindParam(":sessionId", $sessionsId);
        $this->stmt->bindParam(":sessionValue", $sessionsData);
        $this->stmt->execute();
    }

    public function Destroy($sessionsId)
    {
        $this->stmt = $this->prepare("DELETE FROM `sessions`.`sessions` WHERE `id` = :sessionId");
        $this->stmt->bindParam(":sessionId", $sessionsId);
        $this->stmt->execute();
    }

    public function Gc()
    {
        $this->stmt = $this->prepare("DELETE FROM `sessions`.`sessions` WHERE `access` < NOW() - INTERVAL 1 HOUR");
        $this->stmt->execute();
    }
}

now the above code seems to work just fine the only problem is when i write a session in db i get the following insert:

dump from mysql

CREATE TABLE IF NOT EXISTS `sessions` (
  `id` varchar(32) NOT NULL,
  `access` datetime NOT NULL,
  `data` text NOT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `sessions` (`id`, `access`, `data`) VALUES
('lhig71coed8ur81n85iiovje37', '2011-07-25 15:37:57', '');

As you can see the value of the session it's not inserted i only get the session id. on var_dump($sessionsData) i get:

"name|s:6:"Bogdan";"

and for var_dump($sessionsId) i get:

lhig71coed8ur81n85iiovje37

Can you please help? i don't get any errors checked xampp logs setup display errors on error reporting everything i knew even in php.ini still no error anything used even try catch blocks. thank you very much for reading this and helping me out.

Bogdan
  • 693
  • 7
  • 26
  • Can you confirm if $sessionsData does have values? Try echoing it before processes. – ariefbayu Jul 25 '11 at 14:36
  • 1
    That var_dump looks suspicious. It's not valid `serialize()` output - is there any HTML/xml stored in the session array that might be getting "hidden" by a browser view? What do you see in the browser's view-source? – Marc B Jul 25 '11 at 14:59
  • @Marc B: The `var_dump` looks really well for session data. `serialize()` does not work properly with session data, I think you mix this a bit because it's close, but session data is [a list of variable names with their serialized values](http://stackoverflow.com/questions/6722874/what-is-the-php-binary-serialization-handler/6723154#6723154) like so `({varname}|{serialized($varname)})*`. – hakre Jul 25 '11 at 15:12
  • serialize() couldn't care less it's session data. It's just another data structure, basically `serialize($_SESSION)`. A valid serialized session array would at bare minimum start with `a:...`. `|` is not a valid separator. – Marc B Jul 25 '11 at 15:25
  • @Marc B: Well you should better try yourself, the function is not `serialize()` but [`session_encode()`](http://php.net/manual/en/function.session-encode.php). Read as well the topmost note on that manual page. – hakre Jul 25 '11 at 15:27
  • Afaik, also suhosin will do some encrypting, so if you have that running you even get a seemingly nonsensical string there because of that encryption. Still shouldn't be empty of course. – Wrikken Jul 25 '11 at 15:29
  • are you sure you can serialize sessions i though session_decode() and session_decode were for that if my memory doesn't cheat me. – Bogdan Jul 25 '11 at 15:39
  • @Hakre: where's session_encode being called, though? – Marc B Jul 25 '11 at 15:40
  • @Marc B: In PHP, PHP does this for you before passing the data to your session save handler. The encoding can vary as Wrikken pointed out as well, the session serialize handler can be changed, I already linked that as well. I just pointed to `session_encode()` because it allows you to inspect that internal process and to demonstrate that session serialization differs from `serialize()`. The function's output changes if you change the [session serialize handler](http://www.php.net/manual/en/session.configuration.php#ini.session.serialize-handler) value. – hakre Jul 25 '11 at 15:45

1 Answers1

1

I found a flaw in your implementation which results in deleting any session data:

return $this->stmt->fetchAll();

in

public function Read($sessionsId)

That function must return a string, in your case the data from the data field.

But you're returning an array (as it looks like - can't specifically say because the actual database is hidden, PDO/MySQLi?).

However it's highly likely that unserializing the session data (see session_decode()) will fail, hence the session data will become empty and then saved again (as an empty string).

This should be the cause of your problem. Fix it by returning the string data from the database.


Next to that I suspect a kind of encoding issue but I'm not entirely sure that this causes it. But just consider the following:

The session data is binary data, not text. You could change your table definition and access accordingly. In MySQL there is the BLOB Type for that, and bindParam() could be helped with PDO::PARAM_LOB data type specifier.

Probably this type of change will cure your issue. Otherwise it will make sure that you store the data un-altered which is what you want in any case. Stick to binary-safe handling for session data.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • @ hackre: changed mode to BLBO type i've tried your advice didn't work i get [BLOB - 0octețs] in that field. – Bogdan Jul 25 '11 at 15:23
  • @ silent for the echo: The Session Id is : lhig71coed8ur81n85iiovje37 The Value of Session Id is : name|s:6:"Bogdan"; on var_dump string(18) "name|s:6:"Bogdan";" string(26) "lhig71coed8ur81n85iiovje37" on print_r name|s:6:"Bogdan"; lhig71coed8ur81n85iiovje37 all three are function function write so i get the data until that step that's for sure. in the first post i've ate some letters there i apologize was hungry a little but i ate something now. as for the source code i don't see nothing wrong @ hakre thank you for that document bookmarked and still reading. – Bogdan Jul 25 '11 at 15:25
  • @Bogdan: I see, but I think you should still stick to BLOB instead of text to store the data (when it works) as binary and not text. – hakre Jul 25 '11 at 15:30
  • @hrake i will take your advice and use it :) – Bogdan Jul 25 '11 at 15:36
  • @Bogdan: I probably found the culprit, see the edited answer. – hakre Jul 25 '11 at 15:41
  • @ hakre made the necesary modifications and pasted the new source: http://pastebin.com/v0Nt9sdq. you were right it works fine now. i didn't know that after i call $_SESSION['name'] = 'Bogdan'; will write and read after then write and parse null data to write and get no data into mysql. Now i get [BLOB - 18octețs] and on each page i check i get the session :D. The answer was so obvius and it was in front of my eyes been spending two days this was the third day when i tried to find the problem and fix it few hours ago i even tried with blob like your advice and didn't work. :) – Bogdan Jul 25 '11 at 16:07
  • Okay I move that edit above the blob part then. You're welcome ;) – hakre Jul 25 '11 at 16:08
  • i hope someone else who will try and learn and understand the flow of data for sessions will find this topic usefull for me it is thank you everyone for your help thank you hackre very much for taking time and answering and reading all that crappy code.:D By the way forgot to answer your question i'm using and PDO If anyone who reads this or already did got any advices i`m happily to take them. – Bogdan Jul 25 '11 at 16:09
  • @Bogdan: Just accept this question as answer (see here: http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) so others can see your question got answered. – hakre Jul 25 '11 at 16:11